gpt4 book ai didi

c# - Xunit 多个 IClassFixtures

转载 作者:太空狗 更新时间:2023-10-30 00:23:37 25 4
gpt4 key购买 nike

我的问题是如何在一个测试类中设置多个夹具?

但是 Zoo 类的构造函数不能处理多个 fixture。

例如:

public class Zoo : IClassFixture<Tiger>, IClassFixture<Wolf>, IClassFixure<Bird>
{
private IFixture fixture;
public Zoo(IFixture fixture)
{
this.fixture = fixture;
}

[Fact]
public void TestAnimal()
{
//Arrange
int actualBonesCount = this.fixture.BonesCount;
int expectedBonesCount = 2;

//Act & Assert
Assert.Equal(expectedBonesCount, actualBonesCount );
}
}

虎类

public class Tiger : FixtureBase
{
public Tiger()
{
this.BonesCount = 4;
}
}

鸟类类

public class Bird: FixtureBase
{
public Bird()
{
this.BonesCount = 2;
}
}

测试夹具基类

public class FixtureBase : IFixture
{
public int BonesCount { get; set; }
}

和界面

public interface IFixture
{
int BonesCount { get; set; }
}

最佳答案

首先,让我们记忆一下我们什么时候想在 xUnit 中使用 Class Fixtures:

When to use: when you want to create a single test context and share it among all the tests in the class, and have it cleaned up after all the tests in the class have finished.

如您所说,您希望将 Zoo 测试类中的方法重用于实现测试。既然实现使用继承,为什么不对测试类也使用继承呢?

public abstract class Zoo
{
protected readonly IFixture Fixture;

protected Zoo(IFixture fixture)
{
Fixture = fixture;
}

[Fact]
public void TestAnimal()
{
//Arrange
int actualBonesCount = Fixture.BonesCount;
int expectedBonesCount = 2;

//Act & Assert
Assert.Equal(expectedBonesCount, actualBonesCount);
}
}

public class BirdTests : Zoo, IClassFixture<Bird>
{
public BirdTests(Bird fixture)
: base(fixture)
{
}
}

public class TigerTests : Zoo, IClassFixture<Tiger>
{
public BirdTests(Tiger fixture)
: base(fixture)
{
}
}

不过,我真的不明白您希望每个测试如何通过,因为您在通用测试中将 BonesCount 硬编码为 2。

关于c# - Xunit 多个 IClassFixtures,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36319420/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com