Spring和Junit整合

Spring和Junit整合

步骤

  1. 导入Junit的基础包
  2. 导入Spring集合的Junit包
    • spring-test-4.3.8.RELEASE.jar
  3. 在测试类中加上注解

    • @RunWith 创建容器,替换原有运行器

    • @ContextConfiguration 给容器指定加载的配置文件

    • 声明全局变量对象且注入对象

    • 代码

/**
 * 测试类
 */
//帮我们创建容器
@RunWith(SpringJUnit4ClassRunner.class)
//指定创建容器的时候加载哪个配置文件
@ContextConfiguration("classpath:applicationContext.xml")
public class ClassTest {

    /**
     * 注入对象
     * @Resource属性name 填的是Spring配置的bean的id
     */
    @Resource(name="User")
    private User user;

    /**
     * 使用Spring结合的Junit拿到对象
     */
    @Test
    public void getJunitUser(){
        System.out.println(user);
    }
}

猜你喜欢

转载自blog.csdn.net/kato_op/article/details/80247361