【问题标题】:Spring: How to get spring applicationContext in a Testng test class, if I can NOT extend AbstractTestNGSpringContextTestsSpring:如果我不能扩展 AbstractTestNGSpringContextTests,如何在 Testng 测试类中获取 spring applicationContext
【发布时间】:2016-12-22 01:43:13
【问题描述】:
我的测试已经扩展了一个抽象的 BaseIntegrationTest 类,所以不能 extends AbstractTestNGSpringContextTests 类 - 就像我们通常对 Testng Spring 集成测试所做的那样,我不希望我的 BaseIntegrationTest 加载 spring 应用程序上下文(extends AbstractTestNGSpringContextTests ) 因为有很多子类测试不需要上下文(它有一个 DB 实体),而且大多数时候我会排除当前需要 DB 连接进行集成测试的测试。所以偶尔我需要运行这个基于 Testng 的测试,它已经扩展了一些类并且仍然需要 contextAware(我试过 implements ApplicationContextAware 这对我不起作用,也许我做错了?)。你会怎么做?
【问题讨论】:
标签:
java
spring
testng
integration-testing
【解决方案1】:
这就是 Spring 与 TestNG 集成的方式——您必须扩展 AbstractTestNGSpringContextTests。或者,您可以在测试中手动实例化 Spring:
new ClassPathXmlApplicationContext("context1.xml", "context2.xml")
但这不允许您使用其他类型的注释,例如@Transactional。您可能可以通过 TestNG 侦听器编写自己与 Spring 的集成(嗯..为什么 Spring 不使用它?),但这需要一些时间来实现和调试 :)
另外,我想提一下扩展您自己的基类并不是一个好主意。虽然不幸的是这很常见。一种更好(更易于阅读,OOP 友好)的方法是使用您的通用逻辑创建单独的类和函数。然后在您的测试中显式调用它们。