最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

spring boot - I want to Mock internal method calls of a method present in same class - Stack Overflow

programmeradmin1浏览0评论

I have a SpringBoot Service class. I am writing Junit for one of the method which internally calls multiple method of the same class. Internal method also calls another method. I tried using when-thenReturn, but isn'tworking for me. Please give me some leads as I am very much new to Mockito and Junit. I am getting error while making resttemplate call hence I mocked that. Also my testcase for only thirdMethod(-) is working as expected. Also, I am only mocking expected response from public method not private.

    @Service
    public class MyService{
     public void flow(RequestObject request){
             //request processsing
             firstMethod(firstRequestObj);
             //some logic
             secondMethod(secondRequestObj);
             //some logic
         }
         private FirstResponse firstMethod(FirstRequestObj firstRequestObj){
            //some logic 
            thirdMethod(thirdRequestObj);
            //some logic
            return firstResponse;
         }
         private SecondResponse secondMethod(SecondRequestObj secondRequestObj){
            //some logic 
            thirdMethod(thirdRequestObj);
            //some logic
            return secondResponse;
         }
         public ResponseEntity<ThirdResponse> thirdMethod(ThirdRequestObj thirdRequestObj){
            //some logic 
            try {
                      ResponseEntity<ThirdResponse> response = restTemplate.exchange(
                       url, HttpMethod.POST, entity, ThirdResponse.class);

                      return response ;
                } catch (Exception e) {
                   //exception handled
                }

         }
    }
    @InjectMock @Spy 
    Myservice myService;
   
    @ParameterizedTest
        @DisplayName("Should check the flow")
        @MethodSource("com.web.test.utilities.TestUtils#getRequest")
        public void flowTest(Request request){
             when(restTemplate.exchange(ArgumentMatchers.<String>any(), eq(HttpMethod.POST), 
                ArgumentMatchers.<HttpEntity>any(),
                eq(String.class))).thenReturn(any(ResponseEntity.class));

             when(myService.thirdMethod(any())).thenReturn(any());
             myService.flow(someRequest);
             //myService.flow(any());
        }
发布评论

评论列表(0)

  1. 暂无评论