课前的Junit(非静态)

Rom*_*man 78 java junit

是否有任何最佳实践可以让Junit在测试文件中执行一次函数,它也不应该是静态的.

喜欢@BeforeClass非静态功能?

这是一个丑陋的解决方案:

@Before void init(){
    if (init.get() == false){
        init.set(true);
        // do once block
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我不想做的事情,我正在寻找一个集成的junit解决方案.

Upg*_*ave 38

一个简单的if语句似乎也很好用:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:test-context.xml"})
public class myTest {

    public static boolean dbInit = false;

    @Autowired
    DbUtils dbUtils;

    @Before
    public void setUp(){

        if(!dbInit){

            dbUtils.dropTables();
            dbUtils.createTables();
            dbInit = true;

        }
    }

 ...
Run Code Online (Sandbox Code Playgroud)

  • 请参阅[此处](http://stackoverflow.com/questions/12087959/junit-run-set-up-method-once/31117171#31117171),了解此方法的更新,该方法适用于使用继承的测试类。 (2认同)

Esp*_*pen 35

使用空构造函数是最简单的解决方案.您仍然可以覆盖扩展类中的构造函数.

但它并不是所有继承的最佳选择.这就是JUnit 4使用注释的原因.

另一个选择是在factory/util类中创建一个helper方法,让该方法完成工作.

如果您使用的是Spring,则应考虑使用@TestExecutionListeners注释.像这样的测试:

@RunWith(SpringJUnit4ClassRunner.class)
@TestExecutionListeners({CustomTestExecutionListener.class, 
     DependencyInjectionTestExecutionListener.class})
@ContextConfiguration("test-config.xml")
public class DemoTest {
Run Code Online (Sandbox Code Playgroud)

Spring AbstractTestExecutionListener包含例如您可以覆盖的空方法:

public void beforeTestClass(TestContext testContext) throws Exception {
    /* no-op */
}
Run Code Online (Sandbox Code Playgroud)


Kar*_*tik 18

如果您不想为一次初始化设置静态初始值设定项,而不是特别关于使用JUnit,请查看TestNG.TestNG支持使用各种配置选项的非静态一次性初始化,所有这些都使用注释.

在TestNG中,这相当于:

@org.testng.annotations.BeforeClass
public void setUpOnce() {
   // One time initialization.
}
Run Code Online (Sandbox Code Playgroud)

对于拆解,

@org.testng.annotations.AfterClass
public void tearDownOnce() {
   // One time tear down.
}
Run Code Online (Sandbox Code Playgroud)

对于TestNG的相当于JUnit 4的@Before@After,你可以使用@BeforeMethod@AfterMethod分别.


rad*_*tao 7

轻松使用@BeforeAllMethods/ @AfterAllMethods注释在实例上下文(非静态)中运行方法,其中所有注入的值都可用.

有一个特殊的测试库:

https://mvnrepository.com/artifact/org.bitbucket.radistao.test/before-after-spring-test-runner/0.1.0

https://bitbucket.org/radistao/before-after-spring-test-runner/

唯一的限制:仅适用于Spring测试.

(我是这个测试库的开发者)