C#测试,如何在测试之间进行延迟?
我有一些测试将调用一些外部服务。它们对我每秒可以调用的API调用有限制,因此当我运行所有测试时,最后一个测试将失败,因为API调用已达到限制 我如何限制并发测试的数量/在之后设置延迟/使那些特殊的测试在一个线程上工作 我的代码是使用TestFixture的普通测试代码,如下所示:C#测试,如何在测试之间进行延迟?,c#,nunit,nunit-3.0,C#,Nunit,Nunit 3.0,我有一些测试将调用一些外部服务。它们对我每秒可以调用的API调用有限制,因此当我运行所有测试时,最后一个测试将失败,因为API调用已达到限制 我如何限制并发测试的数量/在之后设置延迟/使那些特殊的测试在一个线程上工作 我的代码是使用TestFixture的普通测试代码,如下所示: [TestFixture] public class WithExternalResource { SearchProfilesResponse _searchProfilesResponse;
[TestFixture]
public class WithExternalResource
{
SearchProfilesResponse _searchProfilesResponse;
[OneTimeSetUp]
public async Task WithNonExistingProfile()
{
_searchProfilesResponse= await WhenSearchIsCalled(GetNonExistingProfile());
}
[Test]
public void Then_A_List_Of_Profiles_Will_Be_Returned()
{
_searchProfilesResponse.Should().NotBeNull();
}
[Test]
public void Then_Returned_List_Will_Be_Empty()
{
_searchProfilesResponse.Should().BeEmpty();
}
}
您可以使用以下工具将整个夹具限制为单螺纹:
// All the tests in this assembly will use the STA by default
[assembly:Apartment(ApartmentState.STA)]
[TestFixture]
public class AnotherFixture
{
[Test, Apartment(ApartmentState.MTA)]
public void TestRequiringMTA()
{
// This test will run in the MTA.
}
[Test, Apartment(ApartmentState.STA)]
public void TestRequiringSTA()
{
// This test will run in the STA.
}
}
或者,您可以通过以下方式将某些测试提交给单线程:
// All the tests in this assembly will use the STA by default
[assembly:Apartment(ApartmentState.STA)]
[TestFixture]
public class AnotherFixture
{
[Test, Apartment(ApartmentState.MTA)]
public void TestRequiringMTA()
{
// This test will run in the MTA.
}
[Test, Apartment(ApartmentState.STA)]
public void TestRequiringSTA()
{
// This test will run in the STA.
}
}
如果希望在所有测试之间有延迟,可以在设置中添加线程.Sleep()
或拆卸中添加线程.Sleep()
:
[SetUp] public void Init()
{
/* ... */
Thread.Sleep(50);
}
[TearDown] public void Cleanup()
{ /* ... */ }
您不能使用Thread.Sleep()
或Task.Delay()
?这些不是单元测试。单元测试应该模拟外部依赖关系。