I m new to JUnit and Mockitio. When I run the below code, I get, java.lang.NullPointerException: Cannot invoke "org.springframework.http.ResponseEntity.getStatusCodeValue()" because the return value of "com.learnit.testing.MyController.getUser(java.lang.Long)" is null
@Controller
@RequestMapping("/api")
public class MyController {
@Autowired
private MyService service;
@GetMapping("/")
@ResponseBody
public ResponseEntity<Object> getUser(Long id) throws Exception {
return service.myResponse(id);
}
}
@Service
public class MyService {
@Autowired
private MyRepository repository;
public ResponseEntity<Object> myResponse(Long id) throws Exception{
MyData data=repository.findById(id).orElse(null);
if(data!=null)
return new ResponseEntity<>(HttpStatus.OK);
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
Testing
@ExtendWith(MockitoExtension.class)
public class MyTest {
@InjectMocks
private MyController controller;
@Mock
private MyRepository repo;
@Mock
private MyService service;
@Test
public void checkService() throws Exception {
when(repo.findById((long)1)).thenReturn(null);
assertEquals(controller.getUser((long)1).getStatusCodeValue(), 500);
}
}
ResponseEntity. I recommend letting the service return anOptional<MyData>and have the controller transform it into aResponseEntitydepending on whether it's empty (404) or not (OK).