41
votes

I'm writing unit test for core application. Im trying to check, that my class throws exception. But ExpectedException attribute throws compile exception:

Error CS0246 The type or namespace name 'ExpectedException' could not be found (are you missing a using directive or an assembly reference?) EventMessagesBroker.Logic.UnitTests..NETCoreApp,Version=v1.0

My code:

[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);
}

so, is there any correct way to achieve that?

1
Don't use xunit without reading xunit.github.io/docs/comparisons.htmlRuben Bartelink
3 years late...ExpectedException comes from MSTest Nuget...haven't had any luck cross-use that Nuget w/ XunitJohnny Wu

1 Answers

64
votes

Use Assert.Throws on code where exception expected:

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