【问题标题】:JUnit Mockito rest template Null Pointer ExceptionJUnit Mockito 休息模板空指针异常
【发布时间】:2021-06-30 11:09:55
【问题描述】:

我是 JUnit 和 Mockito 框架的新手。在这里,我试图模拟其余模板并希望返回 200 的 HTTP 状态,但它仍然返回空值。有人能告诉我我的实现有什么问题吗?为什么它返回一个空值,而不是 HttpStatus OK 。

Class MyDependencies{

   @Autowired
   RestTemplate template;

}


Class ABC extends MyDependencies{

   void verify(){
       try{
          ResponseEntity<Object> response;
          try{
             response= template.postForEntity("localhost:....",obj,obj);         
           }catch(Exception e){
               throws Exception.......
           }

           if(response.getStatusCodeValue()==200) // When reaches here, Exception is thrown 
                                                 // becoz response is null
                 return new ResponseEntity<>(HttpStatus.OK);
            else
              throw Custom_Exception.....

          }catch(Exception e){    
              throws Exception..... 
          } 
    }
}

测试

Class MyTesting{

    @InjectMocks
    ABC abc;

    @Mock
    RestTemplate template;

    @BeforeEach
    void setUp(){
        abc=new ABC();
        MockitoAnnotations.initMocks(this);
    }

    @Test
    void testingIt(){
         when(template.postForEntity(anyString(),any(),any())).thenReturn(new ResponseEntity<>(HttpStatus.OK));
         Assertions.asserDoesNotThrow(()->abc.verify());
    }
}

【问题讨论】:

  • 您使用的是什么版本的 spring-boot 和 junit?
  • @code_mechanic Junit 5 & Spring 5.2.8
  • 您是否使用MockitoExtension 类在您的测试类中指定了@ExtendWith 注释?
  • 我没用,我在用 MockitoAnnotations.init(this)
  • 无法复制,也无法从系统访问堆栈溢出。它非常安全......所以我只是提出了一个粗略的实现......我在两天前开始学习 JUnit 并且对很多东西感到困惑......

标签: java spring-boot junit mockito


【解决方案1】:

@code_mechanic 是对的,问题在于测试方法提供的匹配器。

而不是下面的测试方法:

when(template.postForEntity(anyString(),any(),any())).thenReturn(new ResponseEntity<>(HttpStatus.OK));

试试这个,提供 url 而不是 anyString() :

when(template.postForEntity(ArgumentMatchers.endsWith("/abc/1"),any(),any())).thenReturn(new ResponseEntity<>(HttpStatus.OK));

这样它会找出 URL 匹配存根,它对我有用。

【讨论】:

    【解决方案2】:

    问题是我们从测试方法提供的匹配器与服务类中的实际函数调用不匹配,因此未执行存根并且响应为空。

    尝试像这样指定当存根

    when(restTemplate.postForEntity(anyString(), any(), Mockito.<Class<String>>any()))
                    .thenReturn(new ResponseEntity<String>("{\"status\" : \"ok\"}", HttpStatus.OK));
    

    在这种情况下,我将String 作为我通过rest 模板发布的实体。您可以在这里使用其他类。

    对此的服务类调用将如下所示

    ResponseEntity<String> answer = template.postForEntity("/abc/1", entity, String.class);
    

    另外,您在测试中的服务类上有 @InjectMocks,因此您不需要这一行

    abc = new ABC();
    

    MockitoAnnotations.initMocks(this) 已经为您做到了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-24
      • 2021-06-15
      • 2016-08-19
      • 1970-01-01
      • 2015-10-07
      • 1970-01-01
      • 2019-04-09
      • 1970-01-01
      相关资源
      最近更新 更多