【问题标题】:One mock in different tests don't work together不同测试中的一个模拟不能一起工作
【发布时间】:2022-11-14 19:04:03
【问题描述】:

我使用 xUnit (c#)。我有一个模拟不同的测试。我为每个测试设置不同的参数。现在,当我一起运行所有测试时,我遇到了一个问题。同班考试

我知道 xUnit 中有测试并行化,但我不能为每个测试创建不同的类

在测试中:

SupplyLimitsMock.SetOrderQuantityInfo(bidId, warehouseId, destinationWarehouseId);

模拟课:

public static readonly ISupplyLimitsClient SupplyLimitsServiceClient = Substitute.For<ISupplyLimitsClient>();

public static List<OrderQuantityInfoInternal> OrderQuantityInfo = new();

private static readonly Fixture Fixture = new();

static SupplyLimitsMock()
{
    SupplyLimitsServiceClient
        .GetQuantityFromOrdersGroupedByLimits(Arg.Any<long[]>(), Arg.Any<CancellationToken>())
        .Returns(_ => OrderQuantityInfo);
}

public static void SetOrderQuantityInfo(long bidId, long warehouseId, long destinationWarehouseId)
{
    OrderQuantityInfo.Clear();
    OrderQuantityInfo.Add(
        Fixture.Build<OrderQuantityInfoInternal>()
            .With(x => x.OrderId, bidId)
            .With(x => x.WarehouseId, warehouseId)
            .With(x => x.DestinationWarehouseId, destinationWarehouseId)
            .Create());
}

【问题讨论】:

  • 给我们看一些代码。并指定您收到的确切错误消息。

标签: c# xunit


【解决方案1】:

XUnit 在每个测试中运行测试类的构造函数。 https://xunit.net/docs/shared-context

因此,您测试的所有常见设置都放入构造函数中。 您在测试本身中放入的所有变体。 你可以这样做:

private readonly ISupplyLimitsClient supplyLimitsServiceClient;

public TestClas()
{
   this.supplyLimitsServiceClient = Substitute.For<ISupplyLimitsClient>();
}

[Fact]
public void Test()
{
   SupplyLimitsMock.SetOrderQuantityInfo(this.supplyLimitsServiceClient, bidId, warehouseId, destinationWarehouseId);
}

在“SupplyLimitsMock”类中:

public static void SetOrderQuantityInfo(ISupplyLimitsClient supplyLimitsServiceClient, long bidId, long warehouseId, long destinationWarehouseId)
{
   var orderQuantityInfo = new();
   orderQuantityInfo.Add(
        Fixture.Build<OrderQuantityInfoInternal>()
            .With(x => x.OrderId, bidId)
            .With(x => x.WarehouseId, warehouseId)
            .With(x => x.DestinationWarehouseId, destinationWarehouseId)
            .Create());

   supplyLimitsServiceClient.GetQuantityFromOrdersGroupedByLimits(
   Arg.Any<long[]>(), Arg.Any<CancellationToken>()).
   Returns(_ => orderQuantityInfo );   
}

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-06
  • 1970-01-01
  • 1970-01-01
  • 2016-05-13
  • 2016-06-14
相关资源
最近更新 更多