How can I test void methods? [duplicate]

大兔子大兔子 提交于 2019-12-19 19:46:09

问题


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?


回答1:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!