简体   繁体   English

模拟 Rest 模板返回 null 响应

[英]Mocked Rest template is returning a null response

I am new to JUnit5 and Mockito framework in springboot.我是springboot中JUnit5和Mockito框架的新手。 Here I am trying to mock the RestTemplate and return a 200 status with a string response.在这里,我试图模拟 RestTemplate 并返回带有字符串响应的 200 状态。 But I am getting a null response and the function throws a Null Pointer Exception.但是我收到了 null 响应,并且 function 引发了 Null 指针异常。 Is there any mistake in the way I am mocking the rest template?我是mocking rest模板的方式有什么错误吗?

Service服务

public class Abc {
  
  @Autowired
  RestTemplate template;

  @Value("${ser.url}")
  String url;

   void validate(String val){
       
       ResponseEntity<String> response;
       try{
            response = template.postForEntity(url, HTTP_ENTITY, String.class);

       } catch(Exception ex ){
             .....
       }     
        sysout(response); //Prints Null

        String res = response.getBody(); //Null Pointer exception
  }
}

Testing测试

class ServiceTest {

    @InjectMocks
    Abc abc; 

    @Mock
    RestTemplate template;

    @BeforeEach
    void setup(){
        MockitoAnnotations.init(this);
    }
 
    @Test
    void testIt(){
        when(template.postForEntity(anyString(), any(), ArgumentMatchers.<Class<String>>any())).
              thenReturn(new ResponseEntity<String>("value",HttpStatus.OK));
        
        abc.validate("abc"); 
    }
}

After long time experiments in the past I have realized that @InjectMocks sometimes works not as expected.经过过去长时间的实验,我意识到@InjectMocks 有时无法按预期工作。 So now I make use of @MockBean instead.所以现在我改用@MockBean。 This code works:此代码有效:

@Service    
public class Abc {
    @Autowired
    RestTemplate template;

    @Value("${ser.url}")
    String url;

    void validate(String val){

        ResponseEntity<String> response = null;
        try{
            response = template.postForEntity(url, new HttpEntity<>(""),
                    String.class);

        } catch(Exception ex ){
             ex.printStackTrace();
        }
        System.out.println(response); //Prints Null

        String res = response.getBody(); //Null Pointer exception
    }    
}

@SpringBootTest
class AbcTest {

    @Autowired
    Abc abc;

    @MockBean
    RestTemplate template;    

    @Test
    void testIt(){
        when(template.postForEntity(anyString(), any(), ArgumentMatchers.<Class<String>>any())).
                thenReturn(new ResponseEntity<String>("value", HttpStatus.OK));

        abc.validate("abc");
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM