【问题标题】:Unable to mock RestTemplate using JUnit 5 in Spring Boot无法在 Spring Boot 中使用 JUnit 5 模拟 RestTemplate
【发布时间】:2020-12-07 20:22:02
【问题描述】:

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

【问题讨论】:

  • 您好,请问您可以发布堆栈跟踪吗?
  • @PMah:编辑了我的问题。

标签: spring spring-boot junit junit5 junit-jupiter


【解决方案1】:

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

This answer 有很好的解释。

【讨论】:

    猜你喜欢
    • 2019-07-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-06
    • 2020-05-01
    • 2018-03-09
    • 2021-08-02
    • 1970-01-01
    • 2021-09-05
    相关资源
    最近更新 更多