Home > Blockchain >  unit testing of controller class which has rest template
unit testing of controller class which has rest template

Time:12-13

I have tried test on controller class, It is not mock the rest template which is in controller class.

@RestController
public class LoginController {

    @RequestMapping(value = "api/v1/login", method = RequestMethod.POST)
    public String Loginpostmethod(@RequestBody LoginUser login) {

        String url = "https://jira2.domain.com/rest/auth/1/session";
        String username = login.getUsername();
        String password = login.getPassword();
        String authStr = username   ":"   password;
        String base64Creds = Base64.getEncoder().encodeToString(authStr.getBytes());
        HashMap<String, String> map = new HashMap<>();
        map.put("username", username);
        map.put("password", password);
        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", "Basic "   base64Creds);
        headers.set("Content-Type", "application/json");
        headers.set("Accept", "application/json");
        RestTemplate restTemplate = new RestTemplate();
        HttpEntity<HashMap<String, String>> entity = new HttpEntity<>(map, headers);
        
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
        return response.getBody();
        
    }    
}

controller test class

public class LoginControllerTest {
    
    @Mock
    RestTemplate mockrestTemplate;
    private String testUrl = "https://jira2.domain.com/rest/auth/1/session";
    
    @MockBean
    LoginUser mocklogin;
    
    @InjectMocks
    LoginController loginController;
    
    @Test
    public void TestPostMethodSuccess() throws  Exception{
        LoginUser mocklogin=new LoginUser();
        mocklogin.setUsername("testusername");
        mocklogin.setPassword("testpassword");
        
        
        HashMap<String, String> map = new HashMap<>();  
        map.put("username", "username");
        map.put("password", "password");
        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", "Basic");
        headers.set("Content-Type", "application/json");
        headers.set("Accept", "application/json");
        
        HttpEntity<?> request = new HttpEntity<>(map, headers);

        ResponseEntity<String> response = new ResponseEntity<>("respons",HttpStatus.OK);
        
        
        Mockito.when(mockrestTemplate.exchange(testUrl, HttpMethod.POST, request, String.class)).thenReturn(response);
   
        assertEquals(200,response.getStatusCodeValue());
        loginController.Loginpostmethod(mocklogin);
    
    }

This what I have done is this is the proper way to test the controller class, It should call the api inside the controller class have a rest template so I have mocked the rest template which has the null value and assert function also is not working.When I use the verify syntax for when and then,the error as wanted but not invoked.

CodePudding user response:

You have to use @WebMvcTestfor testing the controller layer. It will configure a MockMvc for you such that you can use it to define the HTTP request you want to send to the controller and then verify if the returned HTTP response if what you expect.

Refer this for more details about how to do it .

CodePudding user response:

Using mock Mvc,

 @RunWith(SpringJUnit4ClassRunner.class)
@AutoConfigureMockMvc
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
@ActiveProfiles("test")
public class LoginControllerTest {
    
    @Autowired
    private MockMvc mockMvc;
    
    @Mock
    LoginUser mocklogin;
    
    @InjectMocks
    LoginController loginController;
    
    @Test
    public void TestPostMethodSuccess() throws  Exception{
        LoginUser mocklogin=new LoginUser();
        mocklogin.setUsername("testusername");
        mocklogin.setPassword("testpassword");
        
        this.mockMvc.perform(MockMvcRequestBuilders
                .post("/api/v1/login")
                .contentType(MediaType.APPLICATION_JSON)
                .content(asJsonString(mocklogin))
                .accept(MediaType.APPLICATION_JSON))
                .andDo(print())
                .andExpect(MockMvcResultMatchers.status().isOk());
            
        }
    public static String asJsonString(final Object obj) {
        try {
            final ObjectMapper mapper = new ObjectMapper();
            final String jsonContent = mapper.writeValueAsString(obj);
            System.out.println(jsonContent);
            return jsonContent;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    
}

facing the error,

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.web.client.ResourceAccessException: I/O error on POST request for "https://jira2.domain.com/rest/auth/1/session": jira2.domain.com; nested exception is java.net.UnknownHostException: jira2.domain.com
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1014)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:681)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
    at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:72)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:764)
    at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:167)
    at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134)
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
    at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134)
    at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
  • Related