我正在使用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));
但现在我想编写一些负面单元测试,检查某些方法不会被调用,并且会抛出异常。
例如:
"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());
非常感谢