ExpectedException xunit .net core

Timur Lemeshko picture Timur Lemeshko · Dec 23, 2016 · Viewed 13.8k times · Source

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?

Answer

Dmitry picture Dmitry · Dec 23, 2016

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