无法在 Spring 引导中使用 JUnit 5 模拟 RestTemplate

Unable to mock RestTemplate using JUnit 5 in Spring Boot

试图模拟 restTemplate postForEntity() 但它返回 null 而不是我在 thenReturn() 中传递的 ResponseEntity 对象。

服务实施class

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

内测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);
}

错误

在执行测试用例时,正在调用实际服务。当它尝试在 service impl class 中调用 resttemplate 时,它​​返回 null。

尝试在 transactionHistoryResponse 上调用 getBody() 抛出 NullPointerException

在您的模拟设置中,只有当您传入的参数是 Class<Transaction> 对象 Transaction.class 时,匹配器 ArgumentMatchers.eq(Transaction.class) 才会匹配。这不是你想要的;您希望它匹配 type Transaction 的任何内容。为此,请使用 ArgumentMatchers.any(Transaction.class).

有很好的解释。