2017-10-19 127 views
1

我使用Visual Studio附带的测试框架以及NSubstitute来单元测试一个需要系统ID的方法,并在系统找不到时引发异常在数据库中...NSubstitute:Assert不包含抛出的定义

public VRTSystem GetSystem(int systemID) 
{ 
    VRTSystem system = VrtSystemsRepository.GetVRTSystemByID(systemID); 
    if (system == null) 
    { 
    throw new Exception("System not found"); 
    } 
    return system; 
} 

(在这种情况下,似乎很奇怪,有一个具体的商业案例这种方法需要它抛出一个异常,为返回一个空系统不接受其使用)

我想编写一个测试来检查系统不存在时是否引发异常。目前,我有以下...

[TestMethod] 
public void LicensingApplicationServiceBusinessLogic_GetSystem_SystemDoesntExist() 
{ 
    var bll = new LicensingApplicationServiceBusinessLogic(); 
    try 
    { 
    VRTSystem systemReturned = bll.GetSystem(613); 
    Assert.Fail("Should have thrown an exception, but didn't.); 
    } 
    catch() { } 
} 

通过不嘲讽库,通过VrtSystemsRepository.GetVRTSystemByID()返回的将是无效的制度,引发的异常。虽然这有效,但对我来说却是错误的。我不希望在测试中需要try/catch块。

NSubstitute docs有暗示我应该可以测试这个如下的例子...

[TestMethod] 
public void GetSystem_SystemDoesntExist() 
{ 
    var bll = new LicensingApplicationServiceBusinessLogic(); 
    Assert.Throws<Exception>(() => bll.GetSystem(613)); 
} 

但是,如果我尝试这在我的测试代码,我得到Throws以红色突出显示,与错误消息“断言不包含定义抛出

现在,我没有真正确定该网页上的样本覆盖我的情况下,作为测试代码指定所测试的方法抛出一个异常,这我不明白,因为我认为这个想法的测试是单独测试该方法,并测试在各种情况下会发生什么。但是,即使没有这一点,我不明白为什么Assert.Throws方法不存在。

任何任何想法?

编辑: DavidG指出Assert.Throws可能是NUnit的一部分,而不是MS框架,这将解释为什么它不被识别。如果是这样,我目前正在测试正确的方式来做到这一点?

+1

您正在使用哪种测试框架? 'Assert.Throws'可能是NUnit。 – DavidG

+0

@DavidG啊,忘了补充一点,对不起。我正在使用VS附带的MS。我会更新这个问题。 –

+1

DavidG提到的@AvrohomYisroel引用的文档使用NUnit进行断言。如果不使用该框架,则可以使用['ExpectedExceptionAttribute Class'](https://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.unittesting.expectedexceptionattribute.aspx) – Nkosi

回答

2

正如DavidG所述引用的文档使用NUnit进行断言。

如果不使用该框架可以使用ExpectedExceptionAttribute Class

[TestMethod] 
[ExpectedException(typeof(<<Your expected exception here>>))] 
public void GetSystem_SystemDoesntExist() { 
    var bll = new LicensingApplicationServiceBusinessLogic(); 
    bll.GetSystem(613); 
} 

如果预期没有抛出异常这将失败。

+1

更好的是,添加一个AssertThrows()方法,它更加简洁。有关信息,请参阅此MSDN页面https://msdn.microsoft.com/library/jj159340.aspx#sec18 –

相关问题