userdetails。不能将用户强制转换为MyUser Spring Boot Junit

时间:2018-12-16 15:48:28

标签: java spring-boot junit spring-security

我正在尝试编写遇到上述错误的测试用例。下面是测试用例功能

@Test
@WithMockUser(username="user@example.com", password="Test@777", roles="Role Manager")
public void getDataSuccess() throws Exception {

    mockMvc.perform(get("URL" ))
            .andDo(print())
            .andExpect(status().isInternalServerError());
}

在控制器类中,我得到了发生错误的安全上下文

MyUser user = (MyUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
Long uId = Long.valueOf(user.getId());

下面是MyUser类

MyUser.java

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

public class MyUser implements UserDetails {

    // properties

    public MyUser ( MyJwtUserDetails userDetails , String userToken , Collection<? extends GrantedAuthority> authorities) {
        this..
}

错误:

java.lang.ClassCastException: org.springframework.security.core.userdetails.User cannot be cast to com.example.MyUser

看起来@WithMockUser正在传递用户对象,而它期望UserDetails。如何将UserDetails对象而不是User发送给控制器?

0 个答案:

没有答案