I have some void methods and I need to test them, but I'm not sure about how to do it. I just know how to test methods that return something, using Assert. Someone knows how to do it? Do you guys know some links with exercices in this style?
Using the verify() Method Whenever we mock a void method, we do not expect a return value. That is why we can only verify whether that method is being called or not. Features of verify() : Mockito provides us with a verify() method that lets us verify whether the mock void method is being called or not.
A method's influence should be kept as local as possible. A good way to do this is to not change the state of the class/global variables or that of the parameters passed. Doing this means, that unless you then return an output, your code is meaningless, and hence, avoid Void.
void methods can do everything a normal method can, except return things. That indeed won't work (not sure if it will give a compiler error or just result in nothing getting printed, never tried something like that).
You can test two things:
First approach is simple (NUnit sample):
var sut = new Sut();
sut.Excercise(foo);
Assert.That(sut.State, Is.EqualTo(expectedState)); // verify sut state
Second approach requires mocks (Moq sample):
var dependencyMock = new Mock<IDependency>();
dependencyMock.Setup(d => d.Something(bar)); // setup interaction
var sut = new Sut(dependencyMock.Object);
sut.Excercise(foo);
dependencyMock.VerifyAll(); // verify sut interacted with dependency
Well, you also can test if appropriate exceptions are thrown.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With