【发布时间】:2021-08-15 16:18:27
【问题描述】:
我想对assignApplicationsToUser 进行单元测试。给出了 applicationId 和用户 ID 的列表,并且我有一个 URL 来验证用户。我遇到了下面提到的异常。
java.lang.NullPointerException: Cannot invoke "com.fasterxml.jackson.databind.JsonNode.asText()" because the return value of "com.fasterxml.jackson.databind.JsonNode.get(String)" is null
AssignmentService.java
public class AssignmentService implements AssignemetServiceInterface {
@Autowired
AppInterceptor appInterceptor;
@Autowired
AssignmentRepository assignmentRepository;
@Autowired
private RestTemplate restTemplate;
private String uri="http://localhost:8080/api/users/"+uuid;
@Override
public List<String> assignApplicationsToUser(List<String> applications, String uuid)
throws SQLException, RequestEntityNotFoundException {
HttpHeaders headers = new HttpHeaders();
headers.set("token", appInterceptor.getLoggedInUser());
HttpEntity<String> requestEntity = new HttpEntity<>(null, headers);
String result = restTemplate.exchange(uri, HttpMethod.GET, requestEntity, String.class).getBody();
ObjectMapper objectMapper = new ObjectMapper();
List<String> response = new ArrayList<>();
JsonNode responseJson = objectMapper.readTree(result);
if (responseJson.get("data") == null
&& responseJson.get("error").get("status").asText().equals("NOT_FOUND")) {
throw new RequestEntityNotFoundException(uuid, "find");
}
for (String application : applications) {
ApplicationAssignment isAssigned = assignmentRepository.findOneByApplicationId(application);
if (isAssigned != null) {
isAssigned.setIsUser(true);
response.add(application + " reassigned to "+ uuid);
isAssigned.setAssignedTo(uuid);
this.assignmentRepository.save(isAssigned);
}
else {
ApplicationAssignment newApplication = new ApplicationAssignment(application, uuid, true);
this.assignmentRepository.save(newApplication);
response.add(application + " assigned successfully");
}
}
return response;
}
}
样本输入: { 应用程序:["APP001","APP002","APP003","APP004"], uuid:“用户1” }
已编辑: 我已经添加了相同的示例响应。
{
"data": {
"id": "fa727274-5a74-428a-b0f6-501eebafd8e8",
"name": "Akash",
"email": "AkashTyagi@fico.com",
"phone": 8799190991,
"isActive": true,
"createdBy": "abhishekjaiswal@fico.com",
"updatedBy": null,
"creationTimeStamp": "2021-08-11T11:23:05.356+00:00",
"updationTimeStamp": null
},
"error": null,
"timeStamp": "2021-08-16T05:02:04.866+00:00",
"success": true
}
AssignmentServiceTest.java
@RunWith(MockitoJUnitRunner.class)
@SpringBootTest
public class AssignmentServiceTest {
private static final Logger LOGGER = LoggerFactory.getLogger(AssignmentServiceTest.class);
@InjectMocks
private AssignmentService assignmentService;
@Mock
private AssignmentRepository assignmentRepo;
@Mock
private AppInterceptor appInterceptor;
@Mock
private RestTemplate restTemplate;
ObjectMapper objectMapper;
String jsonString="{\r\n"
+ " \"data\": {\r\n"
+ " \"id\": \"fa727274-5a74-428a-b0f6-501eebafd8e8\",\r\n"
+ " \"name\": \"Akash\",\r\n"
+ " \"email\": \"AkashTyagi@fico.com\",\r\n"
+ " \"phone\": 8799190991,\r\n"
+ " \"isActive\": true,\r\n"
+ " \"createdBy\": \"abhishekjaiswal@fico.com\",\r\n"
+ " \"updatedBy\": null,\r\n"
+ " \"creationTimeStamp\": \"2021-08-11T11:23:05.356+00:00\",\r\n"
+ " \"updationTimeStamp\": null\r\n"
+ " },\r\n"
+ " \"error\": null,\r\n"
+ " \"timeStamp\": \"2021-08-16T05:02:04.866+00:00\",\r\n"
+ " \"success\": true\r\n"
+ "}";;
JsonNode mock;
@BeforeEach
private void setUp() throws JsonMappingException, JsonProcessingException {
objectMapper = new ObjectMapper();
mock = org.mockito.Mockito.mock(JsonNode.class);
}
@Test
public void test_assignApplicationsToUser() throws NullPointerException, SQLException, RequestEntityNotFoundException, IndexOutOfBoundsException,JsonProcessingException, URISyntaxException{
LOGGER.info("Begin of test_assignApplicationToUser method");
ApplicationAssignment applicationAssignment = new ApplicationAssignment("1","u1",true);
ApplicationAssignment savedApplicationAssignment = new ApplicationAssignment("1","u2",true);
ResponseEntity<String> myEntity = new ResponseEntity<String>("{\r\"error\":null\r}",HttpStatus.ACCEPTED);
Mockito.when(restTemplate.exchange(
ArgumentMatchers.anyString(),
ArgumentMatchers.any(HttpMethod.class),
ArgumentMatchers.any(),
ArgumentMatchers.<Class<String>>any())).thenReturn(myEntity);
Mockito.when(appInterceptor.getLoggedInUser()).thenReturn("abhishek@fico.com");
Mockito.when(mock.get("data")).thenReturn(mock);
Mockito.when(mock.get("error")).thenReturn(mock);
Mockito.when(mock.get("error").asText()).thenReturn("FOUND");
LOGGER.info("Node value "+ mock.asText());
Mockito.when(assignmentRepo.findOneByApplicationId("1")).thenReturn(applicationAssignment);
Mockito.when(assignmentRepo.save(ArgumentMatchers.any())).thenReturn(savedApplicationAssignment);
// Mock the input List of applications
List<String> listOfApplication = new ArrayList<>();
listOfApplication.add("app1");
listOfApplication.add("app2");
List<String> response = assignmentService.assignApplicationsToUser(listOfApplication,"u1");
assertEquals(response.get(0),"app1 assigned successfully");
}
}
【问题讨论】:
标签: spring unit-testing junit