Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I test void methods? [duplicate]

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?

like image 320
Vinicius Seganfredo Avatar asked Dec 16 '13 16:12

Vinicius Seganfredo


People also ask

How do you verify a void method?

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.

How do you avoid void methods?

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.

Can void methods print things?

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).


1 Answers

You can test two things:

  • State changes after void method call (state-based testing)
  • Interaction with dependencies during void method call (interaction testing)

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.

like image 127
Sergey Berezovskiy Avatar answered Oct 07 '22 19:10

Sergey Berezovskiy