Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/332.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 带有Junit测试用例的ClassCastException_Java_Spring_Spring Boot_Junit - Fatal编程技术网

Java 带有Junit测试用例的ClassCastException

Java 带有Junit测试用例的ClassCastException,java,spring,spring-boot,junit,Java,Spring,Spring Boot,Junit,我正试图为一个Spring Boot微服务应用程序编写Junit测试用例,在这个应用程序中,我面临着ClassCastException @Mock Authentication authentication; @Mock AuthenticatedUser authUser; @Before public void setUp(){ mockMvc = MockMvcBuilders.webAppContextSetup(applicationContext).build();

我正试图为一个Spring Boot微服务应用程序编写Junit测试用例,在这个应用程序中,我面临着ClassCastException

@Mock
Authentication authentication;

@Mock
AuthenticatedUser authUser;

@Before
public void setUp(){
    mockMvc = MockMvcBuilders.webAppContextSetup(applicationContext).build();
    authentication = Mockito.mock(Authentication.class);
}

@Test
@WithMockUser(username="myuser@test.com")
public void postApiSucess()  throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    mockMvc.perform(post("/myapi/").content(mapper.writeValueAsString(customEventsTrace))
            .contentType(MediaType.APPLICATION_JSON)
            .with(authentication(SecurityContextHolder.getContext().getAuthentication())))
            .andDo(print())
            .andExpect(status().isOk())
            .andExpect(content().contentType(Test.APPLICATION_JSON_UTF8));
}
现在,当它点击控制器并面对语法时

AuthenticatedUser authUser = (AuthenticatedUser) SecurityContextHolder.getContext().getAuthentication()
                .getPrincipal();
它给出了如下例外情况:

java.lang.ClassCastException: org.springframework.security.core.userdetails.User cannot be cast to com.demo.example.AuthenticatedUser
而AuthenticatedUser实现UserDetails

public class AuthenticatedUser implements UserDetails

这里我做错了什么?

Nicholas注释在Spring应用程序中是“正确的”,通常调用getPrincipal()会返回UserDetail对象

从spring安全部分来看,它应该足以处理UserDetail对象,而不是用户(AuthenticatedUser)的应用程序代表


可能来自Baeldung的以下链接会对您有所帮助:或者再次阅读:
User
不能转换为
AuthenticatedUser
,而不是
UserDetails
当我运行应用程序并发送相同的承载令牌时,它是如何工作的?好的,这是另一部分。您将在此处找到一个示例代码,并在此处找到JWT Baerer令牌的Baeldung测试示例