mapper正常运行没问题,运行JUnit测试时,mapper就报错了

mapper正常运行没问题,运行JUnit测试时,mapper就报错了

问题描述:

Spring boot + mybatis-plus项目,正常运行时没问题,运行JUnit测试时,mapper就报错了,不能用,报NullpointerException。
看了网上很多都说是少了@RunWith(SpringJUnit4ClassRunner.class),但是我加上了还是一样

但是我正常跑项目是没问题的,就是Junit会报错,就不知道为什么

单元测试类:

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.howie.Application;
import com.howie.entity.TestEntity;
import com.howie.mapper.TestMapper;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class SpringBootTestUnit {

    @Autowired
    TestMapper mapper;


    @Test
    public void test() {
        String testId = "test1";
        System.out.println("Junit test...");
        LambdaQueryWrapper<TestEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(TestEntity::testId, testId);
        mapper.select(wrapper);
    }
}

报错信息如下:

org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.exceptions.PersistenceException: 
### Error querying database.  Cause: java.lang.NullPointerException
### The error may exist in com/howie/mapper/TestMapper.java (best guess)
### The error may involve com.howie.mapper.TestMapper.selectOne
### The error occurred while executing a query
### Cause: java.lang.NullPointerException

这三个注解缺一不可
@RunWith(SpringJUnit4ClassRunner.class)

//指定启动类
@SpringApplicationConfiguration(classes = Application.class)

//由于是Web项目,Junit需要 模拟ServletContext,因此我们需要给我们的测试类加上@WebAppConfiguration。
@WebAppConfiguration

你好,修改 @RunWith注解为 @RunWith(SpringRunner.class) 试试