zoukankan      html  css  js  c++  java
  • Spring与junti的整合

    junit之前的写法:

    //在Before中注入service类
    private IUserService userService;
        @Before
    public void setUp() throws Exception {
    //使用xml的方式
      ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
    //使用注解的方式
      ApplicationContext applicationContext = new AnnotationConfigApplicationContext(SpringConfiguration.class);
    userService = applicationContext.getBean(IUserService.class);
     }

    Spring与junit整合:

       不需要手动创建Spring容器,  自动把bean注入到测试类

    1、导入spring-test的依赖,  需要junit

    <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-test</artifactId>
          <version>4.3.3.RELEASE</version>
    </dependency>

    2、在测试类使用spring-test的注解

       @RunWith(class)

       @ContextConfiguration(指定配置文件)

    //测试类运行的环境,在spring环境下运行,在测试类, 注入Spring容器的bean
    @RunWith(SpringJUnit4ClassRunner.class)
    //在创建spring容器时,指定加载哪个配置文件  - - 相当于之前的手动获取对象
    @ContextConfiguration("classpath:applicationContext.xml")
    public class UserServiceImplTest {
    
        @Autowired //注入IUserService
        private IUserService userService;
        
        @Test
        public void testFindUserById() {
            userService.findUserById(2);
        }
  • 相关阅读:
    软件工程第一次作业
    邮件服务器的搭建
    将博客搬至CSDN
    古典密码加密解密之多表代换
    Nginx + Tomcat 负载均衡配置详解
    openstack i版搭建教程
    IIS、apache、tomcat服务器虚拟主机配置
    SMTP邮件发送命令
    hadoop集群安装
    信息管理系统(java)
  • 原文地址:https://www.cnblogs.com/64Byte/p/13113806.html
Copyright © 2011-2022 走看看