This question already has an answer here:
- Unit testing void methods? 11 answers
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?
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.
来源:https://stackoverflow.com/questions/20615968/how-can-i-test-void-methods