【问题标题】:How do I create a base test class in Xunit to test interface implementations?如何在 Xunit 中创建一个基本测试类来测试接口实现?
【发布时间】: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();
  }
}

【问题讨论】:

    标签: c# xunit


    【解决方案1】:

    工作方式完全相同...

    public abstract class IDoSomethingTestBase
    {
      protected readonly IDoSomething InstanceUnderTest;
    
      protected IDoSomethingTestBase(IDoSomething instanceUnderTest){
        InstanceUnderTest = instanceUnderTest;
      }
    
      [Fact]
      public void BasicTest()
      {
        Assert.AreEqual("a_string", InstanceUnderTest.SearchString("a_string", ".*");
      }
    }
    

    实际测试类:

    public class ThisDoesSomething_Tests : IDoSomethingTestBase
    {
      public ThisDoesSomething_Tests(): base(new ThisDoesSomething()) { }
    }
    

    【讨论】:

    • 谢谢,但是如何针对实例类调试测试呢?测试方法在基类中。
    • 在 Visual Studio 中,它们将在测试资源管理器中显示为单独的测试类(基类本身不会显示)(右键单击测试并选择调试)。在 VS Code 中有一个方便的插件可以做同样的事情:marketplace.visualstudio.com/…
    猜你喜欢
    • 1970-01-01
    • 2015-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多