【问题标题】:Junit throws NullPointerException on EntityManagerJunit 在 EntityManager 上抛出 NullPointerException
【发布时间】:2021-01-12 10:24:31
【问题描述】:

我正在运行 Junit Test 正在抛出 NullPointerException 的案例这是我的 Junit 测试类结构

   @RunWith(SpringJUnit4ClassRunner.class)
   public class EmployeeTest {

      @InjectMocks
      EmployeeRepository empRepo;        

      @InjectMocks
      EmployeeService empService;

      @Mock
      EntityManager entityManager;

       List<Employee> empList=new ArrayList<Employee>();
      @Before
       public void setUp() throws Exception {
        MockitoAnnotations.initMocks(this);
      }


     @Test
     public void getEmployyeList(){
       Employee e = new Employee(111,'Raunak','kumar','Hero Inc');
       List<Employee> empList=empService.getAllEmployee();
       Employee e1 = empList.stream().filter(emp->emp.getEmpId()==111).findAny().get();
       assertEquals(e,e1);
     }

   }

在EmployeeService 上我使用EntityManager 看起来像

    public class EmployeeService{

     @Autowired
     EntityManager em;

     public List<Employee> getAllEmployee(){
           return  em.createNativeQuery("select e.* from employee e").getResultList();
     }
   }

当我是debugging 时,代码发现em.createNativeQuery("select e.* from employee e") 返回null。从Rest API 它工作正常。

试过

 when(empRepo.findAll()).thenReturn(empList);
     assertThat(users, containsInAnyOrder(
                hasProperty("lastName", is("Kumar"))
        ));

但是empRepo.findAll()也返回[]

【问题讨论】:

    标签: java spring spring-boot junit junit4


    【解决方案1】:

    你必须在你的测试用例 (getEmployyeList) 中使用 mockito 的 when 和 thenReturn 来存根模拟实体管理器,如下所示,这应该可以解决 NPE

    @Test
    public void getEmployyeList(){
        Employee e = new Employee(111,'Raunak','kumar','Hero Inc');
        Query query = mock(Query.class);
        when(entityManager.createNativeQuery(anyString())).thenReturn(query);
        doReturn(Arrays.asList(e)).when(query).getResultList();
        List<Employee> empList=empService.getAllEmployee();
        Employee e1 = empList.stream().filter(emp->emp.getEmpId()==111).findAny().get();
        assertEquals(e,e1);
    }
    

    【讨论】:

    • 不,你不是在重写,所谓的模拟是从单元测试中删除外部依赖项的行为,以便围绕它创建一个受控环境。通常,我们模拟与我们要测试的类交互的所有其他类。所以在这种情况下,我们改为对数据库连接进行存根,并“愚弄”我们的类认为它正在与真正的 EntityManager 对话,而实际上,EntityManager 是一个 Mockito 存根。这样,我们可以完全控制数据库连接返回的内容,而无需处理实际的数据库。希望这会有所帮助
    • @manikantgautam 我已编辑答案,请立即尝试
    • @Abhisekkumar 再次编辑,您现在可以查看吗
    • 这行不通我在query和NPE仍然存在The method thenReturn(javax.persistence.Query) in the type OngoingStubbing&lt;Query&gt; is not applicable for the arguments (org.springframework.data.jpa.repository.Query)
    • @Abhisekkumar asp 根据您的错误,似乎对查询类使用了错误的导入。您应该使用正确的查询类导入,即。测试用例类中的 javax.persistence.Query。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-31
    • 1970-01-01
    • 2020-06-22
    • 2014-11-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多