gpt4 book ai didi

c# - NUnit 相当于 JUnit 的规则

转载 作者:行者123 更新时间:2023-12-02 09:22:36 26 4
gpt4 key购买 nike

C# 中是否存在与 JUnit 规则等效的内容?我的意思是一种避免在几个不同的测试中重复相同的 [SetUp][TearDown] 行的方法。而不是:

[SetUp]
public void SetUp()
{
myServer.connect();
}

[TearDown]
public void TearDown()
{
myServer.disconnect();
}

...将逻辑放入可以在多个测试中声明为字段的规则中:

public MyRule extends ExternalResource {
@Override
protected void before() throws Throwable
{
myServer.connect();
};

@Override
protected void after()
{
myServer.disconnect();
};
};

然后

class TestClass
{
@Rule MyRule = new MyRule();
...
}

最佳答案

您可以实现自己的 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
}
}

关于c# - NUnit 相当于 JUnit 的规则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35021623/

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