What is the preferred way to handle multiple test cases in Xunit?

I switched to using Xunit for unit tests from NUnit. With NUnit, I would create one method with several test cases that have the same result. For example, the following NUnit unit test checks the validation of the class constructor, in particular the variable "name". The name cannot be empty, empty or whitespace. The test checks the correctness of the output of ArgumentNullException:

[Test] [TestCase(null)] [TestCase("")] [TestCase(" ")] [ExpectedException(typeof(ArgumentNullException))] public void Constructor_InvalidName_ExceptionThrown(string name) { // action make_Foo(name); } private make_Foo(string name) { return new Foo(name); } 

Here is how I implemented this with Xunit:

  [Fact] public void Constructor_InvalidName_ExceptionThrown() { Assert.Throws<ArgumentNullException>(() => new Foo(null)); Assert.Throws<ArgumentNullException>(() => new Foo("")); Assert.Throws<ArgumentNullException>(() => new Foo(" ")); } 

This seems bad for two reasons: I have a few statements about what should be a β€œsingle” test, and with test cases embedded in a method (which can be a lot more complicated in some other unit tests).

What is the preferred way to handle multiple test cases in Xunit?

+7
c # unit-testing nunit xunit
source share
1 answer

You can use the Theory attribute with the same effect:

 [Theory()] [InlineData(null)] [InlineData("")] [InlineData(" ")] public void Constructor_InvalidName_ExceptionThrown(string name) { Assert.Throws<ArgumentNullException>(() => new Foo(name)); } 

I'm not sure that xUnit has an attribute a equivalent to ExpectedException . If there is, I would not use it .

It is used there as an ExpectedException attribute in xUnit, but has since been deprecated in favor of Assert.Throws .

+9
source share

All Articles