我使用 xUnit、SubSpec 和 FakeItEasy 进行单元测试。
到目前为止,我已经创建了一些积极的单元测试,如下所示:
"Given a Options presenter"
.Context(() =>
presenter = new OptionsPresenter(view,
A<IOptionsModel>.Ignored,
service));
"with the Initialize method called to retrieve the option values"
.Do(() =>
presenter.Initialize());
"expect the view not to be null"
.Observation(() =>
Assert.NotNull(view));
"expect the view AutoSave property to be true"
.Observation(() => Assert.True(view.AutoSave));
但现在我想编写一些负面单元测试并检查某些方法是否不会被调用,并且会引发异常
e.g.
"Given a Options presenter"
.Context(() =>
presenter = new OptionsPresenter(view,
A<IOptionsModel>.Ignored,
service));
"with the Save method called to save the option values"
.Do(() =>
presenter.Save());
"expect an ValidationException to be thrown"
.Observation(() =>
// TODO
);
"expect an service.SaveOptions method not to be called"
.Observation(() =>
// TODO
);
我可以看到 FakeItEasy 有一个 MustNotHaveHappened 扩展方法,而 xUnit 有一个 Assert.Throws 方法。
但我如何将它们组合在一起呢?
我想要测试的异常应该在调用 Save 方法时发生。所以我猜我应该在 Presenter.Save() 方法调用周围包装一个 Assert.Throws 方法,但我认为 Presenter.Save 方法应该在 .Do(() => ...
您能否建议我的单元测试是否应如下所示或其他内容?
"Given a Options presenter"
.Context(() =>
presenter = new OptionsPresenter(view,
model,
service));
"expect the Presenter.Save call to throw an Exception"
.Observation(() =>
Assert.Throws<FluentValidation.ValidationException>(() => presenter.Save()));
"expect the Service.SaveOptions method not to be called"
.Observation(() =>
A.CallTo(() => service.SaveOptions(A<IOptionsModel>.Ignored)).MustNotHaveHappened());
非常感谢