【发布时间】:2020-02-14 00:55:47
【问题描述】:
我正在使用 C# 和 XUnit 为类库编写测试套件。库中有许多实现接口的类。我可以简单地将接口实现的相同测试复制粘贴到每个测试类中,但我想知道是否有使用一些测试基类的更简洁的解决方案,它可以继承并自动运行,而无需在每个测试类中依次调用每个方法.
这个article on codeproject 演示了如何在mstest 中使用标有TestClass 的抽象基类来完成。下面给出一个摘要。但是我不知道是否有使用 xunit 的等价物。有谁知道如何解决这个问题? xunit 文档说在 mstest 中没有与 TestClass 等效的东西。
界面
public interface IDoSomething
{
int SearchString(string stringToSearch, string pattern);
}
许多实现接口的类之一
public class ThisDoesSomething : IDoSomething
{
public int SearchString(string stringToSearch, string pattern);
{
// implementation
}
}
接口测试基类
[TestClass]
public abstract class IDoSomethingTestBase
{
public abstract IDoSomething GetDoSomethingInstance();
[TestMethod]
public void BasicTest()
{
IDoSomething ids = GetDoSomethingInstance();
Assert.AreEqual("a_string", ids.SearchString("a_string", ".*");
}
}
测试类实现接口的测试类
[TestClass]
public class ThisDoesSomething_Tests : IDoSomethingTestBase
{
public override IDoSomething GetDoSomethingInstance()
{
return new ThisDoesSomething();
}
}
【问题讨论】: