2013-02-11 34 views
12

मैं का उपयोग करता है एक वसंत परीक्षण है:@RunWith (SpringJUnit4ClassRunner.class) का उपयोग करके, क्या आप ApplicationContext ऑब्जेक्ट तक पहुंच सकते हैं?

@RunWith(SpringJUnit4ClassRunner.class) 

परीक्षण के पुराने तरीके के विपरीत, वसंत परीक्षण आधार वर्ग से विस्तार, वहाँ ApplicationContext कि वसंत से लोड किया गया है करने के लिए उपयोग करने के लिए कोई स्पष्ट रास्ता प्रतीत होता है @ContextConfiguration

मैं अपने परीक्षण विधियों से ApplicationContext ऑब्जेक्ट का उपयोग कैसे कर सकता हूं?

धन्यवाद!

उत्तर

13

के @Autowired विशेषता जोड़ें स्प्रिंग प्रलेखन

@Autowired ApplicationContext

ApplicationContextAware इंटरफेस, आप कर सकते हैं को लागू करने के लिए एक विकल्प के रूप में की Integration Testing अनुभाग से किसी फील्ड या सेटर विधि पर @Autowired एनोटेशन के माध्यम से अपने टेस्ट क्लास के लिए एप्लिकेशन संदर्भ इंजेक्ट करें। उदाहरण के लिए:

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration 
public class MyTest { 

    @Autowired 
    private ApplicationContext applicationContext; 

    // class body... 
} 
3

ApplicationContext

@Autowired ApplicationContext applicationContext; 
3

मैं इस का उपयोग करें:

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration("classpath:applicationContext.xml") 
@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = false) 
@FixMethodOrder(MethodSorters.NAME_ASCENDING) 
public class MyClassTest 
{ 
} 

और पथ -> Source -> निर्माण परियोजना के लिए जाना आपके applicationContext.xml

मैं Maven उपयोग करती हैं इसलिए applicationContext.xmlsrc/main/resources किया जा रहा है के स्थान जोड़ें।

आप इस विधि का उपयोग करते हैं आप, उदाहरण के लिए परीक्षण के लिए एक बहु applicationContext हो सकता है:

@ContextConfiguration("classpath:applicationContext_Test.xml") 

या

@ContextConfiguration("classpath:applicationContext_V01.xml")