我有以下测试类:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
public class TransactionServiceTests {
@Rule
public MockitoRule mockitoRule = MockitoJUnit.rule();
@Mock
private MessagingService mockMessagingService;
@Mock
private CustomerRepository mockCustomerRepository;
@Autowired
TransactionService transactionService;
@Test
public void testTransactionBetweenCustomersAndBalanceOfReceiver() {
int AMOUNT = 50;
// prepare your test data unless you always expect those values to exist.
Customer customerReceiver = new Customer();
customerReceiver.setName("TestReceiver");
customerReceiver.setBalance(12);
mockCustomerRepository.save(customerReceiver);
Customer customerSender = new Customer();
customerSender.setName("TestSender");
customerSender.setBalance(50);
mockCustomerRepository.save(customerSender);
int expectedReceiverAmount = customerReceiver.getBalance() + AMOUNT;
int expectedSenderAmount = customerSender.getBalance() - AMOUNT;
transactionService.makeTransactionFromSenderToReceiver(customerSender, customerReceiver, AMOUNT);
assertEquals(expectedSenderAmount, customerSender.getBalance());
assertEquals(expectedReceiverAmount, customerReceiver.getBalance());
}
}
这是交易服务。类本身:
@Service
public class TransactionService {
private MessagingService messagingService;
private CustomerRepository customerRepository;
private static final Logger log = LoggerFactory.getLogger(TransactionService.class);
@Autowired
public TransactionService(MessagingService messagingService, CustomerRepository customerRepository){
Assert.notNull(messagingService, "MessagingService cannot be null");
this.messagingService = messagingService;
Assert.notNull(customerRepository, "CustomerRepository cannot be null");
this.customerRepository = customerRepository;
}
public void makeTransactionFromSenderToReceiver(Customer sender, Customer receiver, int amount) {
if (sender.getBalance() >= amount) {
sender.setBalance(sender.getBalance() - amount);
receiver.setBalance(receiver.getBalance() + amount);
customerRepository.save(sender);
customerRepository.save(receiver);
}
else {
throw new RuntimeException();
}
}
}
在测试期间,它将上述用户添加到我的实时数据库中,甚至在测试完成后仍将它们留在那里。我可以通过某种方式告诉 Mockito 不要碰我的数据库吗?或者说这完全不可能?
“模拟”您的存储库方法调用。另外,使用@InjectMocks
反而@Autowired
for TransactionService
。你还可以使用MockitoJUnitRunner
。
如何模拟存储库调用:
when(customerRepository.save(sender)).thenReturn(someSenderInstance);
要验证是否已调用模拟方法调用,请使用:
verify(customerRepository, times(1)).save(sender);
另外,请记住一件事:您正在测试服务!因此,所有对数据库的调用都应该被模拟。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)