[英]Spring: How to get spring applicationContext in a Testng test class, if I can NOT extend AbstractTestNGSpringContextTests
My test already extends an abstract BaseIntegrationTest class, so can't extends AbstractTestNGSpringContextTests
class - as we normally do with Testng Spring integration tests, and I don't want my BaseIntegrationTest to load the spring application context (by extends AbstractTestNGSpringContextTests
) because there are a lot more sub-class tests that don't need the context (which has a DB entity), and most of the time I will exclude current test that requires the DB connection for integration test. 我的测试已经扩展了抽象的BaseIntegrationTest类,因此不能
extends AbstractTestNGSpringContextTests
类-就像我们通常对Testng Spring集成测试所做的那样,并且我不希望BaseIntegrationTest加载spring应用程序上下文(通过extends AbstractTestNGSpringContextTests
),因为存在一个很多不需要上下文的子类测试(具有数据库实体),大多数时候,我将排除需要DB连接进行集成测试的当前测试。 So once in a while I need to run this Testng based test, which extends some class already and still needs to contextAware (I have tried implements ApplicationContextAware
which doesn't work for me, maybe I was doing it it wrong?). 因此,有时我需要运行这个基于Testng的测试,该测试已经扩展了某些类,但仍然需要contextAware(我尝试
implements ApplicationContextAware
,该方法对我不起作用,也许我做错了吗?)。 How would you do it? 你会怎么做?
That's just how Spring integrates with TestNG - you have to extend AbstractTestNGSpringContextTests
. 这就是Spring与TestNG集成的方式-您必须扩展
AbstractTestNGSpringContextTests
。 Alternatively you can manually instantiate Spring in your tests: 另外,您可以在测试中手动实例化Spring:
new ClassPathXmlApplicationContext("context1.xml", "context2.xml")
But that won't allow you to use other kind of annotations like @Transactional
. 但这不允许您使用其他类型的注释,例如
@Transactional
。 Potentially you could write your own integration with Spring over TestNG listeners (hm.. why Spring didn't use it instead?), but that's going to take some time to implement and debug :) 潜在地,您可以通过TestNG侦听器编写与Spring的集成(嗯。为什么Spring不使用它呢?),但这将花费一些时间来实现和调试:)
Also, I'd like to mention that extending your own base classes is not a good idea . 另外,我想提一下, 扩展自己的基类也不是一个好主意 。 Though it's very common unfortunately.
虽然很不幸,这很常见。 A much better (easier to read, OOP-friendlier) way would be to create separate classes and functions with your common logic.
更好的方法(更易于阅读,友好的OOP)将是使用您的通用逻辑创建单独的类和函数。 And then invoke those explicitly in your tests.
然后在测试中显式调用它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.