Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/haskell/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# NSSubstitute:断言不包含抛出的定义_C#_Unit Testing_Nsubstitute - Fatal编程技术网

C# NSSubstitute:断言不包含抛出的定义

C# NSSubstitute:断言不包含抛出的定义,c#,unit-testing,nsubstitute,C#,Unit Testing,Nsubstitute,我正在使用VisualStudio附带的测试框架,以及NSSubstitute对一个方法进行单元测试,该方法采用系统ID,如果在数据库中找不到系统,则抛出异常 public VRTSystem GetSystem(int systemID) { VRTSystem system = VrtSystemsRepository.GetVRTSystemByID(systemID); if (system == null) { throw new Exception("System

我正在使用VisualStudio附带的测试框架,以及NSSubstitute对一个方法进行单元测试,该方法采用系统ID,如果在数据库中找不到系统,则抛出异常

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 () { }
}
通过不模拟存储库,由
vrtsystemrepository.GetVRTSystemByID()
返回的系统将为空,并引发异常。虽然这是可行的,但在我看来是错误的。我没想到在测试中需要try/catch块

我有一个例子,暗示我应该能够测试如下

[TestMethod]
public void GetSystem_SystemDoesntExist()
{
  var bll = new LicensingApplicationServiceBusinessLogic();
  Assert.Throws<Exception>(() => bll.GetSystem(613));
}
[TestMethod]
public void GetSystem\u systemdoesntextest()
{
var bll=新许可证应用程序服务业务逻辑();
Assert.Throws(()=>bll.GetSystem(613));
}
但是,如果我在测试代码中尝试此操作,我会得到以红色突出显示的
Throws
,并显示错误消息“Assert不包含Throws的定义”

现在,我不确定该页面上的示例是否涵盖了我的场景,因为测试代码指定了被测试的方法会引发异常,这一点我并不真正理解,因为我认为测试的想法是让被测试的方法保持独立,并测试在各种场景下发生的情况。然而,即使没有它,我也不明白为什么
Assert.Throws
方法不存在

有人有什么想法吗


Edit:DavidG指出,
Assert.Throws
可能是NUnit的一部分,而不是MS框架,这可以解释为什么它不被认可。如果是这样,我目前测试的方法是否正确?

正如DavidG所提到的,参考文档使用NUnit进行断言

如果不使用该框架,您可以使用

[TestMethod]
[ExpectedException(typeof())]
public void GetSystem\u systemdoesntextest(){
var bll=新许可证应用程序服务业务逻辑();
bll.GetSystem(613);
}

如果未引发预期的异常,则将失败。

您使用的是哪个测试框架<代码>断言.抛出很可能是NUnit的结果。@DavidG啊,忘了添加了,抱歉。我使用的是VS附带的MS one。我将更新问题。@avrohmyisroel,如DavidG所述,引用的文档使用NUnit进行断言。如果不使用该框架,您可以使用或使用扩展方法,像这样更好,添加一个AssertThrows()方法,这会更整洁。有关详细信息,请参阅此MSDN页面
[TestMethod]
[ExpectedException(typeof(<<Your expected exception here>>))]
public void GetSystem_SystemDoesntExist() {
    var bll = new LicensingApplicationServiceBusinessLogic();
    bll.GetSystem(613);
}