我想为此代码创建一个 JUnit 测试:
private Service listsService;
@RequestMapping(method = {RequestMethod.GET}, path = {"id/{id}"})
public ResponseEntity<Object> find(@PathVariable String id) {
LookupResponse lookupResponse = listsService.findById(id);
return new ResponseEntity<>(lookupResponse, HttpStatus.OK);
}
.................
@Override
public LookupResponse findById(String id) {
Optional<Lists> list = ListsRepository.findById(id);
if(list.isPresent())
{
Lists lists = binList.get();
LookupResponse response = LookupResponse.builder()
.countryCode(lists.getCountry())
.category(lists.getType())
.build())
.build();
return response;
}
return null;
}
我试过这个:
public class ControllerTest {
@MockBean
private ListsService listsService;
@Autowired
private MockMvc mockMvc;
@Test
void justAnExample() {
LookupResponse lookupResponse = LookupResponse.builder()
.type("123456")
.build();
Mockito.when(listsService.findById(Mockito.anyString())).thenReturn(lookupResponse);
}
}
当我运行代码时出现错误:
Cannot invoke "com.ListsService.findById(String)" because "this.listsService" is null
java.lang.NullPointerException: Cannot invoke "com.ListsService.findById(String)" because "this.listsService" is null
你知道我如何正确实施这个模拟测试吗?