在 C# 中是否有等效于 JUnit 的规则?我的意思是一种避免在几个不同的测试中重复相同[SetUp]和[TearDown]行的方法。代替:
[SetUp]
public void SetUp()
{
myServer.connect();
}
[TearDown]
public void TearDown()
{
myServer.disconnect();
}
Run Code Online (Sandbox Code Playgroud)
...将逻辑放在一个规则中,该规则可以在几个测试中声明为字段:
public MyRule extends ExternalResource {
@Override
protected void before() throws Throwable
{
myServer.connect();
};
@Override
protected void after()
{
myServer.disconnect();
};
};
Run Code Online (Sandbox Code Playgroud)
进而
class TestClass
{
@Rule MyRule = new MyRule();
...
}
Run Code Online (Sandbox Code Playgroud)
小智 5
您可以实现自己的TestActionAttribute类来运行您的测试前和测试后代码。如果您打算在每次测试之前和之后执行相同的操作,您可以在类声明中定义您的自定义属性。
例如:
[MyRule] // your custom attribute - applied to all tests
public class ClassTest
{
[Test]
public void MyTest()
{
// ...
}
}
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class MyRuleAttribute : TestActionAttribute
{
public override void BeforeTest(TestDetails testDetails)
{
// connect
}
public override void AfterTest(TestDetails testDetails)
{
// disconnect
}
}
Run Code Online (Sandbox Code Playgroud)