Search code examples
springspring-bootjunitjunit5junit-jupiter

Unable to mock RestTemplate using JUnit 5 in Spring Boot


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


Solution

  • 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.