首页 > 解决方案 > 我可以将代表传递给 Xunit 理论吗

问题描述

我有兴趣在许多类上重用测试理论,特别是一些需要相同测试的构造函数。我最初的想法是使用委托来执行此功能。

但是,我认为我可能正在尝试重新发明轮子,尽管 C# 具有一些功能,但我认为我正在尝试一种不正确的方法。是否有使用比 InlineData 更正确的方法来支持此类事情的方法。

InlineData 似乎用于注入输入,因此我可能会测试给定测试的许多示例。但是我可以为几种方法提供几个变量并测试 ^x 而不是 *x

[Theory]
[InlineData(input => new ConcreteConstructor(input)) ]
public void Constructor_Should_Not_Throw_Expection (Action<string>)
{
  constructor("SomeString");            
}

注意我认为我应该Func在这种情况下使用作为返回的对象。无论如何,我怀疑这完全是错误的方法,所以这不是主要考虑因素。

标签: xunit.net

解决方案


public static IEnumerable<object[]> TestData()
{
  Action<string> a1 = input => new ConcreteConstructor(input);
  yield return new object[] { a1 };
  Action<string> a2 = input => new AnotherConstructor(input);
  yield return new object[] { a2 };
}

[Theory]
[MemberData(nameof(TestData))]
public void Constructor_Should_Not_Throw_Expection(Action<string> constructor)
{
  constructor("SomeString");
}

推荐阅读