我正在使用x-unit。我们使用测试输出。我们在基类中有一些东西。我们目前像这样注入
ITestOutputHelper
:
public class AnyTestClass : TestBase
{
[Fact]
public void SomeTest()
{
}
public AnyTestClass( ITestOutputHelper output ) : base(output)
{
}
}
而我希望代码看起来像:
public class AnyTestClass : TestBase
{
[Fact]
public void SomeTest()
{
}
}
我非常讨厌必须将委托构造函数放入其中。它总是一样的,它的工作,它使代码变得混乱,它没有为读者添加任何内容,它是重复的代码......而且它只是感觉非常“错误”。
有什么办法可以绕过它吗?我一直认为 x-unit 必须存在于堆栈中,并且堆栈中的其中一个东西必须有对
ITestOutputHelper
的引用,我必须能够通过反射得到它......任何人都做到了可以节省我一些时间寻找吗?
基本上 - 我准备做大量的额外工作或额外计算,以使我们的代码库更干净一些 - 这是一个明显的代码示例,不会给读者增加任何价值。
您现在可以使用 https://github.com/pengweiqhca/Xunit.DependencyInjection
来完成此操作您必须实现 BeforeAfterTest 类。例如:
public class BeforeAfterTestTest
{
public IDependency? Dependency { get; set; }
[Fact]
public void Test() => Assert.NotNull(Dependency);
}
public class TestBeforeAfterTest(IDependency dependency) : BeforeAfterTest
{
public override void Before(object? testClassInstance, MethodInfo methodUnderTest)
{
if (testClassInstance is BeforeAfterTestTest beforeAfterTestTest)
beforeAfterTestTest.Dependency = dependency;
}
}
您这里有示例: