Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ExpectedException xunit .net core

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?

like image 781
Timur Lemeshko Avatar asked Dec 23 '16 13:12

Timur Lemeshko


People also ask

Does xUnit work with .net core?

Sometimes, you want to write tests and ensure they run against several target application platforms. The xUnit.net test runner that we've been using supports . NET Core 1.0 or later, . NET 5.0 or later, and .

How do you write xUnit test cases in .net core?

To write a test you simply create a public method that returns nothing and then decorate it with the Fact attribute. Inside that method you can put whatever code you want but, typically, you'll create some object, do something with it and then check to see if you got the right result using a method on the Assert class.

Is xUnit compatible with .NET framework?

It's an open source unit testing tool for . Net framework that's compatible with ReSharper, CodeRush, TestDriven.Net, and Xamarin. You can take advantage of xUnit.Net to assert an exception type easily.


1 Answers

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)); } 
like image 62
Dmitry Avatar answered Sep 19 '22 11:09

Dmitry