坚持每天写博文,积累下开发中的点点滴滴
- 传统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