44

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?

2
  • 4
    Don't use xunit without reading xunit.github.io/docs/comparisons.html Commented Dec 24, 2016 at 9:38
  • 3 years late...ExpectedException comes from MSTest Nuget...haven't had any luck cross-use that Nuget w/ Xunit Commented Jul 16, 2019 at 16:47

1 Answer 1

73

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));
}
Sign up to request clarification or add additional context in comments.

3 Comments

yeap, i use this way. Think this is only solution
Just for the record, xunit does not support ExpectedException and supports the way shown in the answer. As described in more detail here: xunit.github.io/docs/comparisons.html If you wanted to follow the Triple A syntax for unit testing then you could assign parser.GetType(message) to an Action and assert that your action throws an exception.
We can also use Record.Exception method and later on verify using Assert.NotNull method and Assert.IsType<> method. See richard-banks.org/2015/07/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.