0

试图模拟 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

4

1 回答 1

1

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

这个答案有一个很好的解释。

于 2020-12-07T20:52:39.330 回答