繁体   English   中英

Spring 引导响应实体在单元测试时返回 Null Rest Z9BBF373797BF7CF7BA62C800236

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM