简体   繁体   English

Junit-每次测试结束时的方法

[英]Junit - method at the end of each test

I got a method that I call at the end of every test to reset the streams positions. 我得到了一个方法,该方法在每次测试结束时都会调用,以重置流位置。

Test{
[....]
reset();
}

Is there any elegant way to avoid such a repetition? 有什么优雅的方法可以避免这种重复?

Try @After annotaton, that goes with JUnit. 尝试@After注解,它与JUnit一起使用。 Example from source: 来源示例:

 public class Example {
    File output;
    @Before public void createOutputFile() {
          output= new File(...);
    }
    @Test public void something() {
          ...
    }
    @After public void deleteOutputFile() {
          output.delete();
    }
 }

the other answers suggest the @After annotation on a public method (preferably with name teardown ) which is technically right and a good answer to your question. 其他答案建议在公共方法上使用@After批注(最好使用名称teardown ),这在技术上是正确的,并且是对您问题的良好答案。

But essential properties of unittests is that they need to be fast and independent of each other. 但是单元测试的基本特性是它们必须快速且彼此独立。

Therefore the better approach is to use a fresh mock of the stream with every test. 因此,更好的方法是在每次测试时都使用流的新鲜模拟。 This is best done by using a mocking framework like Mockito, JMock or alike. 最好使用Mockito,JMock之类的模拟框架来完成。

是的,使用@After注释创建新方法。

您应该使用@After注释-表示在每个方法运行结束时都需要完成一些操作。

Use @After annotation. 使用@After注释。

@Test 
public void testSomething() {
   // test goes here
}

@After 
public void doSomethingAfterTest() {
   // reset
}

As others have pointed out, there are the @s: Before and After . 正如其他人指出的那样,有@s: BeforeAfter Class instance methods with these annotations will run before/after every test case. 具有这些批注的类实例方法将在每个测试用例之前/之后运行。

There is also BeforeClass and AfterClass , which I didn't see anyone point out yet. 还有BeforeClassAfterClass ,我还没有看到有人指出。 These @s may be put onto static methods of your class, and those methods will execute before and after all of the tests in your class have completed. 这些@可以放在类的静态方法上,并且这些方法将在类中的所有测试完成之前和之后执行。 It is handy in certain situations. 在某些情况下很方便。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM