Mockito控制器测试出错

e0bqpujr  于 2022-11-08  发布在  其他
关注(0)|答案(1)|浏览(172)

我试着测试我控制器,但是我得到了错误
通缉但不援引:(“9090”);如果您的帐户中有现金,那么您就可以使用该帐户。
然而,与此模拟的交互恰好为1:(accountService.cash“9090”,现金交易邮箱:2f 408960)

@PostMapping("/cash/{accountNumber}")
    public ResponseEntity<TransactionStatus> cash(@PathVariable String accountNumber, @RequestBody CashTransaction cashTransactionRequest) {
        return ResponseEntity.ok(accountService.cash(accountNumber, cashTransactionRequest));
    }

---
    public TransactionStatus cash(String accountNumber, CashTransaction cashTransaction) {
            Account account = this.findAccount(accountNumber);
            cashTransaction.setType(TransactionTypes.CASH_TRANSACTION.getRelation());
            account.post(cashTransaction);
            accountRepository.save(accountMapper.AccountToAccountEntity(account));

            return TransactionStatus.createTransactionStatus(HttpStatus.OK, "");
    }
----
@SpringBootTest
@ContextConfiguration
@AutoConfigureMockMvc
class ControllerTests  {

    @Spy
    @InjectMocks
    private AccountController accountController;

    @Mock
    private AccountService accountService;

    @Mock
    private AccountMapper accountMapper;

    @Mock
    private AccountRepository accountRepository;

    @Test
    public void givenId_Cash_thenReturnJson()
    throws Exception {

        Account account = new Account("James Harden", "9090");

        CashTransaction cashTransaction = new CashTransaction(100.0);

        AccountEntity accountEntity = new AccountEntity();
        accountEntity.setOwner(account.getOwner());
        accountEntity.setAccountNumber(account.getAccountNumber());

        TransactionStatus transactionStatus = new TransactionStatus();
        transactionStatus.setStatus(HttpStatus.OK.name());

        doReturn(account).when(accountService).findAccount( "9090");
        doReturn(transactionStatus).when(accountService).cash("9090", depositTransaction);
        doReturn(accountEntity).when(accountRepository).save(accountEntity);

        ResponseEntity<TransactionStatus> result = accountController.cash( "9090", cashTransaction);
        verify(accountService, times(1)).findAccount("9090");
        assertEquals("OK", result.getBody().getStatus());
    }
kwvwclae

kwvwclae1#

我猜你失踪了

....
@ExtendWith(SpringExtension.class)
@SpringBootTest
@ContextConfiguration
@AutoConfigureMockMvc
class ControllerTests  {
.....

在你的ControllerTest类上面。同时我建议使用@Autowired而不是@Spy和@InjectMocks,并且用@MockBean注解你的模拟服务、Map器和仓库
或(取决于您的使用情形)
使用注解

@ExtendWith(MockitoExtension.class)

那么你就有了一个不启动spring上下文的Mockito测试。你可以删除@SpringBootTest @ContextConfiguration @AutoConfigureMockMvc。反正你不需要@AutoConfigureMockMvc,因为你不执行http调用,而是直接调用RestControllers方法。我不明白为什么你在测试中需要spring上下文,所以我更喜欢使用Mockito测试。由于applicationContext不启动,所以它要快得多。
混合Spring和Mockito测试环境是可行的,但可能会造成奇怪的情况。我通常会尝试留在一个环境中。要么测试一个类,用Mockito模拟所有东西,要么编写一个集成测试,使用Spring实用程序。

相关问题