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));
}
Author by
Timur Lemeshko
Updated on June 27, 2022Comments
-
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 over 7 yearsyeap, i use this way. Think this is only solution
-
Michael A. over 7 yearsJust 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 almost 7 yearsWe can also use
Record.Exception
method and later on verify usingAssert.NotNull
method andAssert.IsType<>
method. See richard-banks.org/2015/07/…