[英]Spring Boot Response Entity Is Returning Null While Unit Testing Rest Controller
我正在嘗試對返回 ResponseEntity 的 Controller 進行單元測試,但是當我使用 restTemplate 對其進行測試時,響應中的值是 null。 請幫忙。
用戶控制器測試:
@MockBean
RoleService roleService;
@Autowired
TestRestTemplate restTemplate;
@Test
public void testGetAllRoles() throws ResourceNotFoundException {
List<Role> roleList = new ArrayList<>();
Role role = new Role(1l, "ROLE_SUPER_ADMIN", "Super Admin");
roleList.add(role);
User user = new User("FirstName", "LastName", "testEmail", "credential", roleList);
when(roleService.getAllRoles()).thenReturn(Arrays.asList(role));
ResponseEntity<List<Role>> response = restTemplate.exchange("/user/getAllRoles", GET,
loggedInAs("testEmail", "ROLE_SUPER_ADMIN"), new ParameterizedTypeReference<List<Role>>() {
});
assertEquals(response.getStatusCode().value(), HttpStatus.OK.value());
System.out.println(response.getBody());
//assertEquals(response.getBody().get(0).getCode(), role.getCode());
}
用戶控制器:
@Autowired
RoleService roleService;
@GetMapping("/user/getAllRoles")
@Operation(summary = "get a list of all Roles")
@PreAuthorize("hasAnyRole('ROLE_SUPER_ADMIN', 'ROLE_SYSTEM_ADMIN', 'ROLE_SALES_USER')")
public ResponseEntity<List<Role>> getAllRoles() throws ResourceNotFoundException {
return responseHelper.response(null, roleService.getAllRoles(), HttpStatus.OK);
}
角色服務:
@Override
public List<Role> getAllRoles() throws ResourceNotFoundException {
List<Role> roles = roleRepository.findAll();
if (CollectionUtils.isEmpty(roles)) {
throw new ResourceNotFoundException(env.getProperty(ConstantsUtil.APP_MODULE_ROLE), env.getProperty(ConstantsUtil.ROLE_NOT_FOUND));
}
return roles;
}
角色:
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
protected Long id;
@Column(name = "code", length = 50)
private String code;
@Column(name = "description", length = 100)
private String description;
@Override
public String getAuthority() {
return code;
}
請幫忙
您需要在此替換您的測試:
List<Role> roleList = new ArrayList<>();
Role role = new Role(1l, "ROLE_SUPER_ADMIN", "Super Admin");
roleList.add(role);
User user = new User("FirstName", "LastName", "testEmail", "credential", roleList);
when(roleService.getAllRoles()).thenReturn(Arrays.asList(role));
ResponseEntity<Object[]> response = restTemplate.getForEntity("/user/getAllRoles", Object[].class);
Object[] objects = response.getBody();
assertEquals(response.getStatusCode().value(), HttpStatus.OK.value());
System.out.println(response.getBody());
使用它
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.