如何测试使用xUnit,SubSpec和FakeItEasy抛出的exception

我正在使用xUnit,SubSpec和FakeItEasy进行unit testing。 到目前为止,我已经创建了一些积极的unit testing,如下所示:

"Given a Options presenter" .Context(() => presenter = new OptionsPresenter(view, A.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)); 

但是现在我想写一些负面unit testing并检查某些方法是否被调用,并抛出exception

例如

 "Given a Options presenter" .Context(() => presenter = new OptionsPresenter(view, A.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方法。

但是我怎么把它们放在一起呢?

我想要测试的exception应该在调用Save方法时发生。 所以我猜我应该在presenter.Save()方法调用周围包装一个Assert.Throws方法,但我认为应该在.Do(()=>中调用presenter.Save方法…

您能否告知我的unit testing是否应该如下所示?

 "Given a Options presenter" .Context(() => presenter = new OptionsPresenter(view, model, service)); "expect the Presenter.Save call to throw an Exception" .Observation(() => Assert.Throws(() => presenter.Save())); "expect the Service.SaveOptions method not to be called" .Observation(() => A.CallTo(() => service.SaveOptions(A.Ignored)).MustNotHaveHappened()); 

非常感谢

我会这样做:

 "Given a Options presenter" .Context(() => presenter = new OptionsPresenter(view, (IOptionsModel)null, service)); "with the Save method called to save the option values" .Do(() => exception = Record.Exception(() => presenter.Save())); "expect an ValidationException to be thrown" .Observation(() => Assert.IsType(exception) ); "expect an service.SaveOptions method not to be called" .Observation(() => A.CallTo(() => service.SaveOptions(A.Ignored)).MustNotHaveHappened() ); 

或者更好的是,为xBehave.net切换SubSpec并引入FluentAssertions : –

 "Given an options presenter" .x(() => presenter = new OptionsPresenter(view, (IOptionsModel)null, service)); "When saving the options presenter" .x(() => exception = Record.Exception(() => presenter.Save())); "Then a validation exception is thrown" .x(() => exception.Should().BeOfType()); "And the options model must not be saved" .x(() => A.CallTo(() => service.SaveOptions(A.Ignored)).MustNotHaveHappened()); 

我没有听说过fakeItEasy或subSpec(你的测试看起来很时髦,所以我可以查看这些:))。 但是,我确实使用xUnit,所以这可能会有所帮助:

我在Assert.ThrowsDelegate中使用Record.Exception

所以类似于:

  [Fact] public void Test() { // Arange // Act Exception ex = Record.Exception(new Assert.ThrowsDelegate(() => { service.DoStuff(); })); // Assert Assert.IsType(typeof(), ex); Assert.Equal("", ex.Message); } 

希望有所帮助。

这是在FakeItEasy中实现这一目标的一种方法。

 Action act = () => someObject.SomeMethod(someArgument); act.ShouldThrow();