无法在Spring Boot中使用JUnit 5模拟RestTemplate [英] Unable to mock RestTemplate using JUnit 5 in Spring Boot
问题描述
尝试模拟restTemplate postForEntity(),但它返回的是null而不是我在thenReturn()内部传递的ResponseEntity对象.
Trying to mock restTemplate postForEntity() but it is returning null instead of ResponseEntity object I am passing inside thenReturn().
服务Impl类
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.
While executing test case, actual service is getting called. When it tries to invoke resttemplate inside service impl class it is returning null.
尝试在transactionHistoryResponse上调用getBody()并引发NullPointerException
Trying to call getBody() on transactionHistoryResponse throwing NullPointerException
推荐答案
在模拟设置中,匹配器ArgumentMatchers.eq(Transaction.class)
仅在您传入的参数为Class<Transaction>
对象Transaction.class
时才匹配.这不是您想要的;您希望它与任何类型 Transaction
匹配.为此,请使用ArgumentMatchers.any(Transaction.class)
.
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)
.
此答案有很好的解释.
这篇关于无法在Spring Boot中使用JUnit 5模拟RestTemplate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!