【问题标题】:Refactoring JUnit rules from tests从测试中重构 JUnit 规则
【发布时间】:2013-11-15 23:48:04
【问题描述】:

我有几个测试并与他们一起使用 junit。在我所有的测试文件中,我都有 junit @Rule 语句。喜欢:

public @Rule
TestWatcher resultReportingTestWatcher = new TestWatcher(this);

我的所有测试文件中都存在此语句和其他一些语句。这种重复的代码让我有点困扰,因为我认为这些行可以移动到一个单独的地方,并且可以从那里使用。

我不太确定这是否可以完成,因为我对junit 很陌生。 需要指导。

【问题讨论】:

    标签: testing junit refactoring code-reuse redundancy


    【解决方案1】:

    您可以将 common Rules 放在父类中:

    public class AbstractTest {
        @Rule public SomeRule someRule = new SomeRule();
    }
    public class YourTest extends AbstractTest {
        @Test public void testMethod() {
            someRule.blah();
            // test some things
        }
    }
    

    【讨论】:

    • 感谢您的回复。另外,这个@Rule 语句可以在某些条件下使用吗?例如:我希望只有在某些条件为真时才执行此语句。
    • 不,它不能 - JUnit 反射性地通过您的测试类并在运行您的测试之前调用任何 @Rules(或任何 @Before 方法)。
    • 您可以根据条件创建自己的规则。
    • @StefanBirkner:您能否参考一些好的教程来创建我自己的@Rule 注释。
    • blog.schauderhaft.de/2009/10/04/junit-rules 这是一个好的开始,但要注意 MethodRule 被 TestRule 取代。你也可以看看System Rules的源码,这是一个简单规则的库。 JUnit's org.junit.rules package 也有一些示例规则。
    猜你喜欢
    • 2017-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多