Unable to mock RestTemplate using JUnit 5 in Spring Boot

落爺英雄遲暮 提交于 2020-12-15 05:06:28

问题


Trying to mock restTemplate postForEntity() but it is returning null instead of ResponseEntity object I am passing inside thenReturn().

Service Impl class

public ResponseEntity<Object> getTransactionDataListByAccount(Transaction transaction) {
    ResponseEntity<Object> transactionHistoryResponse = restTemplate.postForEntity(processLayerUrl, transaction, Object.class);        
    return new ResponseEntity<>(transactionHistoryResponse.getBody(), HttpStatus.OK);
}

Inside Test class

@SpringBootTest
@ActiveProfiles(profiles = "test")
public class TransactionServiceImplTest {

    @MockBean
    private RestTemplate mockRestTemplate;

    @Autowired
    private TransactionServiceImpl transactionService;

    @Test 
    public void getTransactionDataListByAccountTest() throws Exception{
    
    Transaction transaction = new Transaction();
    transaction.setPosAccountNumber("40010020070401");
            
    ArrayList<Object> mockResponseObj = new ArrayList<Object>(); //filled with data

    ResponseEntity<Object> responseEntity = new ResponseEntity<Object>(mockResponseObj, HttpStatus.OK);
    
    when(mockRestTemplate.postForEntity(
            ArgumentMatchers.anyString(), 
            ArgumentMatchers.eq(Transaction.class), 
            ArgumentMatchers.eq(Object.class))).thenReturn(responseEntity);
    

    // THROWING NullPointerException at this line.
    ResponseEntity<Object> actualResponse = transactionService.getTransactionDataListByAccount(transaction);

    
    System.out.println("--- Response ---");
    System.out.println(actualResponse);
}

Error

While executing test case, actual service is getting called. When it tries to invoke resttemplate inside service impl class it is returning null.

Trying to call getBody() on transactionHistoryResponse throwing NullPointerException


回答1:


In your mock setup, the matcher ArgumentMatchers.eq(Transaction.class) will only match if the argument you pass in is the Class<Transaction> object Transaction.class. This is not what you want; you want it to match anything of type Transaction. To do this, use ArgumentMatchers.any(Transaction.class).

This answer has a good explanation.



来源:https://stackoverflow.com/questions/65188821/unable-to-mock-resttemplate-using-junit-5-in-spring-boot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!