DominC
DominC

Reputation: 21

Testing controllers with Authentication class in spring

in my controller methods i'm using Authentication class for getting logged in user data.

It looks like this:

@GetMapping("/somepath")
    public ResponseEntity<SomeType> someMethod(Authentication user){
        ...
    }

and I have no idea how to test it. I tried @WithMockUser annotation, .with(user(...)), and it does't work. Does anyone know how to do it properly?

Upvotes: 1

Views: 89

Answers (1)

Ashutosh
Ashutosh

Reputation: 1107

Ideally speaking if you have followed good coding practices, you will never end up writing test cases for a controller or a data lawyer . Ideally the test cases are used to test some business logic involve in code and by reference we should write all the business into services.

A very less work should be done at controller like request validation.

Anyways below piece of code might help you to test your controller methods.

   MockMvc mvc;
   @Autowired
   WebApplicationContext webApplicationContext;

   protected void setUp() {
      mvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
   }
   protected String mapToJson(Object obj) throws JsonProcessingException {
      ObjectMapper objectMapper = new ObjectMapper();
      return objectMapper.writeValueAsString(obj);
   }
   protected <T> T mapFromJson(String json, Class<T> clazz)
      throws JsonParseException, JsonMappingException, IOException {

      ObjectMapper objectMapper = new ObjectMapper();
      return objectMapper.readValue(json, clazz);
   }


@Test
public void someMethodTest() throws Exception {
   String uri = "/somepath";
   Authentication authentication = new Authentication ();

   String inputJson = super.mapToJson(authentication);
   MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.put(uri)
      .contentType(MediaType.APPLICATION_JSON_VALUE).content(inputJson)).andReturn();

   int status = mvcResult.getResponse().getStatus();
   assertEquals(200, status);
   String content = mvcResult.getResponse().getContentAsString();
   // Assert whatever you want 
   assertEquals();
}

Upvotes: 1

Related Questions