【问题标题】:Spring Boot - Mockito: Unfinished Stubbing detectedSpring Boot - Mockito:检测到未完成的存根
【发布时间】:2021-05-10 18:19:12
【问题描述】:

我是 JUnit 和 Mockito 的新手。有人可以指导如何模拟下面的休息模板吗?我当前的模拟显示错误:未完成的存根

服务

class MyService {

   void func(){
       (SimpleClientHttpRequestFactory).restTemplate.getRequestFactory()).setConnectTimeout(t1);
   }
}

Mockito

Class MyTest {
    @Inject
    MyService service;
    
    @Mock
    RestTemplate template;

    @Test
    void testit(){    
        doNothing().when((SimpleClientHttpRequestFactory)
                   .restTemplate.getRequestFactory())).setTimeout(anyInt();
    }
}

【问题讨论】:

    标签: java spring-boot junit mockito


    【解决方案1】:

    您需要添加 initMocks() 或 openMocks() 来进行模拟初始化:

    @BeforeEach(for Junit5 @Before for Junit4)
    void setUp(){
       initMocks(this);
    }
    

    然后你应该在“when-then”部分声明你的模拟行为:

    when(restTemplate.getRequestFactory()).thenReturn(mock(RequestFactory.class));
    

    使用mockito 为您的方法的调用链存根。

    完整版示例:

    Class MyTest {
        @Inject
        MyService service;
        
        @Mock
        RestTemplate template;
    
        @BeforeEach
        void setUp(){
           initMocks(this);
        }
    
    @Test
    void testit(){
       RestTemplate template = mock(RestTemplate.class);
       ClientHttpRequestFactory factory = mock(ClientHttpRequestFactory.class);
    
       when(restTemplate.getRequestFactory()).thenReturn(template));
       when(template.getRequestFactory).thenReturn(factory);
       etc...
       
    }
    

    }

    【讨论】:

      猜你喜欢
      • 2020-09-07
      • 2014-12-06
      • 1970-01-01
      • 1970-01-01
      • 2021-12-06
      • 1970-01-01
      • 2021-07-14
      • 2022-01-27
      相关资源
      最近更新 更多