【发布时间】:2025-11-23 20:15:01
【问题描述】:
使用 JUnit @BeforeClass 和 Spring @TestExecutionListener beforeTestClass(TestContext testContext) "hook" 有什么区别?如果有区别,在什么情况下使用哪一个?
Maven 依赖项:
弹簧芯:3.0.6.RELEASE
弹簧上下文:3.0.6.RELEASE
弹簧测试:3.0.6.RELEASE
spring-data-commons-core:1.2.0.M1
spring-data-mongodb:1.0.0.M4
mongo-java-driver:2.7.3
junit:4.9
cglib:2.2
使用 JUnit @BeforeClass 注解:
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
@ContextConfiguration(locations = { "classpath:test-config.xml" })
public class TestNothing extends AbstractJUnit4SpringContextTests {
@Autowired
PersonRepository repo;
@BeforeClass
public static void runBefore() {
System.out.println("@BeforeClass: set up.");
}
@Test
public void testInit() {
Assert.assertTrue(repo.findAll().size() == 0 );
}
}
=> @BeforeClass: set up.
=> Process finished with exit code 0
使用 Spring 钩子:
(1) 覆盖 beforeTestClass(TextContext testContext):
import org.springframework.test.context.TestContext;
import org.springframework.test.context.support.AbstractTestExecutionListener;
public class BeforeClassHook extends AbstractTestExecutionListener {
public BeforeClassHook() { }
@Override
public void beforeTestClass(TestContext testContext) {
System.out.println("BeforeClassHook.beforeTestClass(): set up.");
}
}
(2) 使用@TestExecutionListeners 注解:
import org.springframework.test.context.TestExecutionListeners;
// other imports are the same
@ContextConfiguration(locations = { "classpath:test-config.xml" })
@TestExecutionListeners(BeforeClassHook.class)
public class TestNothing extends AbstractJUnit4SpringContextTests {
@Autowired
PersonRepository repo;
@Test
public void testInit() {
Assert.assertTrue(repo.findAll().size() == 0 );
}
}
=> BeforeClassHook.beforeTestClass(): set up.
=> Process finished with exit code 0
【问题讨论】:
标签: junit4 spring-test