4

我需要在每个 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 方法只在第一次执行测试方法之前被调用。它不会在所有其余的之前调用。

是不是配置有问题?任何的想法?

谢谢

4

2 回答 2

13

当您使用 运行 JUnit 类时SpringJUnit4ClassRunner,可以使用 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
    ...
}
于 2012-10-15T12:07:22.923 回答
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
    }
}

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

于 2012-10-15T12:07:11.067 回答