0

I am going to test my controller using springsecurity.

@PostMapping("/xx")
public String xx(Authentication auth){
    String userId = (String)auth.getPrincipal();
    ....
}

I have no idea how to mock Authentication object. Or is there other way to deal with it?

My test shown below

public class MyControllerTest{
    @Autowired
    private XxController xxController;

    private MockMvc mockMvc;

    @Before
    public void setUp() {
        mockMvc = MockMvcBuilders.standaloneSetup(xxController).build();
    }

    @Test
    public void xxtestMethod() throws Exception {

    MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.post(/xx))
            .andExpect(MockMvcResultMatchers.status().isOk())
            .andDo(MockMvcResultHandlers.print())
            .andReturn();
    }
}
3
  • @Deadpool sorry, I did not get your point, do you mean in body?
    – wl.GIG
    Commented Dec 11, 2019 at 4:44
  • Authentication is an object in springsecurity filterchain
    – wl.GIG
    Commented Dec 11, 2019 at 4:46
  • I think this Authentication is not the header thing in http request
    – wl.GIG
    Commented Dec 11, 2019 at 4:48

1 Answer 1

0

For basic auth, after trying different ways to do it, I found this worked for me :

MockMvcRequestBuilders
            .post(urlEndpoint)
            .principal(new MyAuthentication())

Notice that MyAuthentication class implements the Authentication interface

1

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.