我正在运行一组集成测试,虽然其中大部分都在合理的时间范围内完成,但有两个测试正在等待特定条件(准确地说是金融市场条件),它们可能会持续 2-3 小时.所以理想情况下,我想实现两件事:
- 在其他测试完成后开始这两个测试
- 并行运行它们
有没有办法在 NUnit/XUnit(或其他测试运行程序)中实现这一点?
最佳答案
Start those two tests after other tests are finished
您可以将这两个测试保存在一个单独的 nunit 测试项目中,从而允许您单独运行所有其他测试。
对于并行运行测试,这个博客有一篇不错的文章:
https://blog.sanderaernouts.com/running-unit-tests-in-parallel-with-nunit
Mark your test fixtures with the Parallelizable attribute and set the parallel scope to ParallelScope.All.
Create a private class called TestScope and implement IDisposable.
Put all startup and clean-up logic inside the TestScope constructor and .Dispose() method respectively.
Wrap your test code in a using (var scope = new TestScope) { ... } block
[TestFixture]
[Parallelizable(ParallelScope.All)]
public class MyClassTests {
[Test]
public void MyParallelTest() {
using(var scope = new TestScope()) {
scope.Sut.DoSomething();
scope.Repository.Received(1).Save();
}
}
private sealed class TestScope : IDisposable {
public IRepository Repository{get;}
public MyClass Sut {get;}
public TestScope() {
Repository = Substitute.For<IRepository>();
Sut = new MyClass(Repository);
}
public void Dispose() {
//clean-up code goes here
Repository?.Dispose()
}
}
}
您应该采取预防措施以确保在并行运行时,您的测试不会相互干扰。
正如文章所述:
How to safely run tests in parallel
To allow tests to run in parallel without them interfering with each other, I have been applying the following pattern for a while:
- Create a nested private TestScope class that implements IDisposable.
- All initialization or startup code that would go into the SetUp method goes into the constructor of the TestScope class.
- Any clean-up or teardown code that would go into the TearDown method goes into the Dispose method All tests run inside a using block that handles the creation and disposal of the TestScope.
[TestFixture]
[Parallelizable(ParallelScope.All)]
public class MyClassTests {
[Test]
public void MyParallelTest() {
using(var scope = new TestScope()) {
scope.Sut.DoSomething();
scope.Repository.Received(1).Save();
}
}
private sealed class TestScope : IDisposable {
public IRepository Repository{get;}
public MyClass Sut {get;}
public TestScope() {
Repository = Substitute.For<IRepository>();
Sut = new MyClass(Repository);
}
public void Dispose() {
//clean-up code goes here
Repository?.Dispose()
}
}
}
文章提供了更多有值(value)的建议。我建议阅读它,并感谢作者。
关于nunit - 运行长时间运行的 NUnit/xUnit 测试,这样它们就不会阻塞其他测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63331697/