试图模拟 restTemplate postForEntity() 但它返回 null 而不是我在 thenReturn() 内部传递的 ResponseEntity 对象。
服务实现类
public ResponseEntity<Object> getTransactionDataListByAccount(Transaction transaction) {
ResponseEntity<Object> transactionHistoryResponse = restTemplate.postForEntity(processLayerUrl, transaction, Object.class);
return new ResponseEntity<>(transactionHistoryResponse.getBody(), HttpStatus.OK);
}
内部测试类
@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);
}
错误
在执行测试用例时,实际的服务被调用。当它尝试在服务 impl 类中调用 resttemplate 时,它返回 null。
尝试在 transactionHistoryResponse 上调用 getBody() 并抛出 NullPointerException