0

i am trying to write code to my @Controller secured endpoint, here is the most essential parts of that method:

@GetMapping("/{username}")
    public String getUser(@PathVariable("username") String username, @AuthenticationPrincipal SecurityUser u, Model model){
        User user = userService.readByUsername(username);
        List<Post> posts = postService.getPostsByUser_Username(username);


        boolean ifImageIsPresent = false;
        boolean ifFriend = false;
        boolean isAccount = false;

        Friend f = friendService.getFriendByReceiverUsername(username, u.getUsername());

        if(u.getImages().size() > 0){
            ifImageIsPresent = true;
        }

        if(f != null){
            ifFriend = true;
        }

        if(u.getReceivedRequests().contains(f)){
            ifFriend = true;
        }
        if(u.getUsername().equals(username)){
            isAccount = true;
        }

        model.addAttribute("ifFriend", ifFriend);
        model.addAttribute("isAccount", isAccount);
        model.addAttribute("imageIsPresent", ifImageIsPresent);
        model.addAttribute("posts", posts);

        model.addAttribute("user", user);
        model.addAttribute("image", user.getImages());

        model.addAttribute("size", user.getImages().size());
        return "profile-page";
    }

And here is my test method:

@Test
//    @DisplayName("Test requesting specific user information by user id in URL")
    public void getUserByIdTest() throws Exception {
        User user = new User();
        //Fields by which I will check correctness
        user.setFirstName("FirstTest");
        user.setLastName("LastTest");
        user.setPassword("q");
        user.setEmail("[email protected]");
        user.setUsername("q");
        user.setId(444);

        given(userService.readByUsername(user.getUsername())).willReturn(user);

        mockMvc.perform(MockMvcRequestBuilders.get("/users/q"))
                .andExpect(view().name("profile-page"))
                .andExpect(status().isUnauthorized())
                .andExpect(model().attributeExists("user"))
                .andExpect(model().attribute("user", user));
    }

And in respose i get that i`m not authorize, so 401 error.

I tried adding annotation

@WithMockUser(username = "q", password = "q", roles = "USER")

But then in logs i get this error:

Caused by: java.lang.NullPointerException: Cannot invoke "ua.socialnetwork.security.SecurityUser.getUsername()" because "u" is null
    at ua.socialnetwork.controller.UserController.getUser(UserController.java:136)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:568)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:207)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:152)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:117)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:884)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:797)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1080)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:973)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1010)
    ... 137 more

Also, i have tried adding

@Import(SecurityConfig.class)

But it did not help.

I think the problem is in method, because i am using

@AuthenticationPrincipal annotation

But i havent found any solutions how to fix it

I need to somehow login in MockMVC, so i can test my code:D Or think of other methods, but i dont know which ones and actually how, because kind of new to tests

2
  • How are you configuring/initializing MockMvc in your test? Commented May 27, 2023 at 11:09
  • stackoverflow.com/questions/33616386/… – is your controller working outside of the test in the real application? Where is your authentication principal created? How is your authentication manager implemented? Commented May 27, 2023 at 13:31

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.