简体   繁体   中英

xUnit InlineData unexpected result

I've got the following class I'm trying to unit test (example class):

using System;

public class Checker
{
    public bool Check<T>(T valueA, T valueB)
    {
        if (typeof(T) != typeof(string))
            throw new NotSupportedException();
        
        return true;
    }
}

When I call new Checker().Check(null, "test") it correctly returns true but when I use xUnit with InlineData as follows:

[Theory]
[InlineData(null, "test")]
[InlineData("test", null)]
public void TestChecker<T>(T valueA, T valueB)
{
   var checker = new Checker();

   Assert.True(checker.Check(valueA, valueB));
}

Both tests should pass but they don't - instead a NotSupportedException exception is thrown on the first test. According to the Test Explorer... this was passed on the first test:

Namespace.TestChecker<Object>(valueA: null, valueB: "test") - why is T type of object instead of string as when I call it directly and how can I prevent this from happening?

Ok actually there is a better way of achieving this while maintaining InlineData :

[Theory]
[InlineData(null, "test")]
[InlineData("test", null)]
public void TestChecker<T>(T valueA, T valueB)
{
   var checker = new Checker();

   Assert.True(checker.Check((dynamic) valueA, (dynamic) valueB));
}

Although this is not the prettiest because Test Explorer will still show TestChecker<Object>(valueA: null, valueB: "test") but it works...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM