【发布时间】:2022-07-31 18:05:15
【问题描述】:
我正在尝试对返回 ResponseEntity 的 Controller 进行单元测试,但是当我使用 restTemplate 对其进行测试时,response 中的值变为 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;
}
请帮忙
【问题讨论】:
-
您是否调试并收到来自测试的请求,在控制器中停止?
-
是的,我已经调试过了,这是调试时在响应中显示的内容: response = ""
-
ResponseEntity
响应 = testRestTemplate。 getForEntity(FOO_RESOURCE_URL + "/1", String.class);使用 getForEntity -
@MaximBezmen ,实际上我是 Spring Boot 的新手,这意味着什么。你能解释一下我需要做什么吗?
-
getForEntity 这是通过对指定 URL 执行 GET 来检索实体。响应被转换并存储在 ResponseEntity 中。
标签: java spring-boot response resttemplate spring-boot-test