How can I check void methods?

I have some void methods and I need to test them, but I'm not sure how to do this. I just know how to test methods that return something using Assert. Does anyone know how to do this? Do you guys know some links with exercises in this style?

+6
source share
1 answer

You can check two things:

  • State changes after calling void method (state check)
  • Interaction with dependencies during the void method call (interaction testing)

The first approach is simple (NUnit example):

var sut = new Sut(); sut.Excercise(foo); Assert.That(sut.State, Is.EqualTo(expectedState)); // verify sut state 

The second approach requires mocks (Moq pattern):

 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 can also test if appropriate exceptions are selected.

+10
source

All Articles