SpringBoot单元测试时无法注入Repository

@SpringBootTest
public class ApplicationTests {

    @Autowired
    CustomerRepository customerRepository;
    @Test
    public void test1(){
        Customer one = customerRepository.findOne(1);
        System.out.println("==========================");
        System.out.println(one);
        System.out.println("==========================");
    }
}

结果报java.lang.NullPointerException。后来发现启动时调用没问题。说明是spring data JPA在springboot启动时会为继承了JpaRepository的接口创建实现,而单元测试调用时并没有启动。
具体解决:

		<dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-testartifactId>
            <scope>testscope>
        dependency>
@RunWith(SpringRunner.class)
@SpringBootTest
public class ApplicationTests {

    @Autowired
    CustomerRepository customerRepository;
    @Test
    public void test1(){
        Customer one = customerRepository.findOne(1);
        System.out.println("==========================");
        System.out.println(one);
        System.out.println("==========================");
    }

}

加个注解就好了

你可能感兴趣的:(spring,boot)