JUnit - 在方法之前

时间:2012-10-15 11:54:53

标签: java spring junit spring-test

我需要在每个JUnit测试方法之前执行一些代码。要执行这段代码,我使用SpringTest类AbstractTestExecutionListener及其子TransactionContextTestExecutionListener。

这是代码:

public class TransactionContextTestExecutionListener extends AbstractTestExecutionListener{

    private static final Logger logger = Logger.getLogger(TransactionContextTestExecutionListener.class);


    @Override
    public void beforeTestMethod(TestContext testContext) throws Exception {
        Object ctx = testContext.getApplicationContext().getBean(Context.class);
}

我的JUnit类看起来像:

@ContextConfiguration(locations = "classpath:/META-INF/spring-test/tests-context.xml")
@RunWith(SpringJUnit4ClassRunner.class)
@TestExecutionListeners(TransactionContextTestExecutionListener.class)
@Transactional
public class SelectQueryBuilderTest {}

问题是beforeTestMethod方法只在第一次执行之前被调用 测试方法。它没有在所有其余的之前调用。

配置有问题吗?有什么想法吗?

由于

2 个答案:

答案 0 :(得分:13)

当您使用SpringJUnit4ClassRunner运行JUnit类时,可以使用JUnit 4注释:

@Before
public void multipleInit() {
    // Called before each method annotated with @Test
    ...
}

@BeforeClass
public static void initAll() {
    // Called once per class, before any method annotated with @Test is called
    ...
}

答案 1 :(得分:8)

我建议您尝试@Before。例如,考虑为您的测试创建一个基类:

@ContextConfiguration(locations = "classpath:/META-INF/spring-test/tests-context.xml") 
@RunWith(SpringJUnit4ClassRunner.class) 
@TestExecutionListeners(TransactionContextTestExecutionListener.class) 
@Transactional 
public class BaseQueryBuilderTest {
    @Autowired
    private ApplicationContext applicationContext;
    protected Context context;

    @Before
    public void setUp() {
        context = applicationContext.getBean(Context.class);
    }
} 

现在您可以按如下方式编写测试实现:

public class SelectQueryBuilderTest extends BaseQueryBuilderTest {
    @Test
    public void test() {
        // Use context
    }
}

这种方法的一个好处是它将大量元数据封装在基类中,使您不必在所有实际测试类中复制它。