堅持每天寫博文,積累下開發中的點點滴滴
- 傳統spring測試存在問題:
1,每個測試都要重新啓動spring;
2,測試代碼在管理spring容器;應該是spring容器在管理測試代碼;
如何告訴JVM,運行Spring容器.
Spring的測試:
依賴:spring-test-3.2.0.RELEASE.jar
@RunWith(SpringJUnit4ClassRunner.class):表示先啓動Spring容器,把junit運行在Spring容器中
@ContextConfiguration(“classpath:xxx.xml”):表示從哪裏加載資源文件
public class HelloWorldTest {
@Autowired //表示自動裝配
private BeanFactory factory;
@Test
public void testSpringTest() throws Exception {
HelloWorld helloWorld = factory.getBean("springTest", HelloWorld.class);
helloWorld.sayHello();
}
}
若:把@ContextConfiguration(“classpath:xxx.xml”) 寫成@ContextConfiguration
默認去找的當前測試類名-context.xml配置文件,如:HelloWorldTest-context.xml