在junit中使用Autowired注解

一 POM文件: 
junit版本要求大于点等于4.12


 <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.springframework/spring-test -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>4.3.11.RELEASE</version>
      <scope>test</scope>
    </dependency>

二 测试

package com.szc.dao;


import com.szc.pojo.Employee;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import javax.sql.DataSource;

/**
 * Unit test for simple App.
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:beans.xml")
public class BeanTest {

    private ApplicationContext applicationContext=null;

    @Autowired
    private EmployeeRepository employeeRepository;


    @Test
    public void testBean(){
        applicationContext=new ClassPathXmlApplicationContext("beans.xml");
        DataSource dataSource=applicationContext.getBean(DataSource.class);
    }

    @Test
    public void testEmployeeRepository(){
        Employee employee=employeeRepository.findByName("zhangsan");
        System.out.println(employee);
    }

}

猜你喜欢

转载自blog.csdn.net/junj6n/article/details/80559314