首页 > 解决方案 > Junit 在 EntityManager 上抛出 NullPointerException

问题描述

我正在运行抛出的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()也返回[]

标签: javaspringspring-bootjunitjunit4

解决方案


您必须使用 mockito 的 when 和 thenReturn 在您的测试用例(getEmployyeList)中存根模拟实体管理器,如下所示,这应该解决 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);
}

推荐阅读