【问题标题】:ExpectedException xunit .net coreExpectedException xunit .net 核心
【发布时间】:2017-05-09 05:03:55
【问题描述】:

我正在为 core 应用程序编写单元测试。我试图检查我的班级是否抛出异常。但是 ExpectedException 属性会抛出编译异常:

错误 CS0246 类型或命名空间名称“ExpectedException”不能 被发现(您是否缺少 using 指令或程序集 参考?)EventMessagesBroker.Logic.UnitTests..NETCoreApp,Version=v1.0

我的代码:

[Fact]
[ExpectedException(typeof(MessageTypeParserException))]
public void TestMethod1_Error_twoMathces()
{
    var message = "some text";
    var parser = new MessageTypeParser();
    var type = parser.GetType(message);
    Assert.Equal(MessageType.RaschetStavkiZaNalichnye, type);
}

那么,有没有正确的方法来实现呢?

【问题讨论】:

标签: unit-testing asp.net-core .net-core xunit xunit.net


【解决方案1】:

在预期异常的代码上使用Assert.Throws

[Fact]
public void TestMethod1_Error_twoMathces()
{
    var message = "some text";
    var parser = new MessageTypeParser();
    Assert.Throws<MessageTypeParserException>(() => parser.GetType(message));
}

【讨论】:

  • 是的,我用这种方式。认为这是唯一的解决方案
  • 仅作记录,xunit不支持ExpectedException,支持答案中显示的方式。如这里更详细的描述:xunit.github.io/docs/comparisons.html 如果您想遵循 Triple A 语法进行单元测试,那么您可以将 parser.GetType(message) 分配给 Action 并断言您的操作会引发异常。
  • 我们也可以使用Record.Exception方法,稍后使用Assert.NotNull方法和Assert.IsType&lt;&gt;方法进行验证。见richard-banks.org/2015/07/…
猜你喜欢
  • 1970-01-01
  • 2021-10-25
  • 2021-09-07
  • 2023-03-14
  • 1970-01-01
  • 1970-01-01
  • 2017-10-23
  • 1970-01-01
相关资源
最近更新 更多