【发布时间】:2020-07-31 12:31:53
【问题描述】:
我正在尝试对以下类进行单元测试(示例类):
using System;
public class Checker
{
public bool Check<T>(T valueA, T valueB)
{
if (typeof(T) != typeof(string))
throw new NotSupportedException();
return true;
}
}
当我调用new Checker().Check(null, "test") 时,它会正确返回true,但是当我将xUnit 与InlineData 一起使用时,如下所示:
[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));
}
两个测试都应该通过,但它们没有通过 - 而是在第一个测试时引发 NotSupportedException 异常。根据测试资源管理器...这是在第一次测试中通过的:
Namespace.TestChecker<Object>(valueA: null, valueB: "test") - 为什么是T 类型的object 而不是string 当我直接调用它时,我该如何防止这种情况发生?
【问题讨论】:
-
因为编译器将
T推断为checker.Check(valueA, valueB)中的string,而null是string的有效值 -
@PavelAnikhouski 问题不是为什么当调用
new Checker().Check(null, "test")T是string类型时 - 这很明显。问题是为什么当我使用[InlineData(null, "test")]时不会发生这种情况(但是当我使用[InlineData("test", null)]时会发生这种情况 -
第二个测试应该失败,但它不是根据您的断言,第二个测试抛出
NotSupportedException并通过。第一个会失败。你知道,你想测试什么并看到预期的行为吗? -
我猜,这只是一个编译器规则,用于根据参数值确定要推断的类型。更准确地说,这一段Finding the best common type of a set of expressions解释说
-
@AlexanderPetrov 我唯一能找到的就是不要使用
InlineData
标签: c# .net unit-testing xunit