ExpectedException xunit .net core

17,988

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));
}
Share:
17,988
Timur Lemeshko
Author by

Timur Lemeshko

Updated on June 27, 2022

Comments

  • Timur Lemeshko
    Timur Lemeshko almost 2 years

    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?

  • Timur Lemeshko
    Timur Lemeshko over 7 years
    yeap, i use this way. Think this is only solution
  • Michael A.
    Michael A. over 7 years
    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.
  • Brij
    Brij almost 7 years
    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/…