Transferred from: Http://www.coderli.com/junit-spring-test-applicationcontext
The spring framework is used in JUnit unit test cases, directly as follows.
@RunWith (Springjunit4classrunner. Class= {"/spring/applicationcontext.xml" })publicclass Springtest {}
You want to get the ApplicationContext instance. You can add an injection to the ApplicationContext
Runwith (Springjunit4classrunner. Class= {"/spring/applicationcontext.xml" })publicclass springtest {@ autowiredprotected applicationcontext ctx;
Spring has already provided a more convenient base class directly: Abstractjunit4springcontexttests
@ContextConfiguration (locations = {"/spring/applicationcontext.xml") }) Public classSpringtestextendsabstractjunit4springcontexttests { Public<T> T Getbean (class<t>type) {returnApplicationcontext.getbean (type);} PublicObject Getbean (String beanname) {returnApplicationcontext.getbean (beanname);} protectedApplicationContext GetContext () {returnApplicationContext;} }
I add:
If you need a reference in a static class, you can only use the following methods:
Public classTplatforminfotestextendstestbase{Private Staticmyhttpclient Tplatforminfodispose; @BeforeClass Public Static voidSetupbeforeclass () {System.out.println ("***********here init first***************"); Tplatforminfodispose=NewMyhttpclient ("Platform"); Datasourcecontextholder.setdbtype ("DS2"); ApplicationContext CTX=NewClasspathxmlapplicationcontext ("Classpath:web-inf/rest-*.xml"); PFM= Ctx.getbean (tplatforminfomapper.class); Dim= Ctx.getbean (tdeviceinfomapper.class); }
"Go" springtest framework junit Unit test Case Get ApplicationContext instance method