【发布时间】: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