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?

Daniel
  • 9,491
  • 12
  • 50
  • 66
Timur Lemeshko
  • 2,747
  • 5
  • 27
  • 39

1 Answers1

72

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));
}
Dmitry
  • 16,110
  • 4
  • 61
  • 73
  • 1
    yeap, i use this way. Think this is only solution – Timur Lemeshko Dec 23 '16 at 14:51
  • 2
    Just for the record, xunit does not support ExpectedException and supports the way shown in the answer. As described in more detail here: https://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. – Michael A. Jan 19 '17 at 13:50
  • 3
    We can also use `Record.Exception` method and later on verify using `Assert.NotNull` method and `Assert.IsType<>` method. See https://www.richard-banks.org/2015/07/stop-using-assertthrows-in-your-bdd.html – Brij Jul 28 '17 at 09:48