我对Sping Boot 和测试有点陌生。我想测试这个@Service类:
@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 CustomerBalanceExceededException();
}
}
}
在我的工具库中,我有spring-boot-starter-test maven依赖项用于测试。
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
public class CustomerTests
{
@Autowired
private CustomerRepository repository;
@Test
public void testCreate()
{
final Customer customer = new Customer();
customer.setName("CoolGuy");
Assert.notNull(repository.save(customer));
}
}
我目前还不知道如何测试上面定义的@Service类的方法的功能。任何提示都非常感谢。
**EDIT:**我试过写一个测试,但我不认为这是测试这个逻辑的正确方法。任何帮助都将不胜感激:
事务服务测试类
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
public class TransactionServiceTests {
@Autowired
private CustomerRepository repository;
@Autowired
private TransactionService transactionService;
@Test
public void testTransactionBetweenCustomersAndBalanceOfReceiver() {
int AMOUNT = 50;
Customer customerOksana = repository.findByName("Oksana");
Customer customerDeniss = repository.findByName("Deniss");
transactionService.makeTransactionFromSenderToReceiver(customerDeniss, customerOksana, AMOUNT);
assertThat(customerOksana.getBalance()).isEqualTo(customerOksana.getBalance());
}
@Test
public void testTransactionBetweenCustomersAndBalanceOfSender() {
int AMOUNT = 40;
Customer customerOksana = repository.findByName("Oksana");
Customer customerDeniss = repository.findByName("Deniss");
transactionService.makeTransactionFromSenderToReceiver(customerDeniss, customerOksana, AMOUNT);
assertThat(customerDeniss.getBalance()).isEqualTo(customerDeniss.getBalance());
}
}
2条答案
按热度按时间zy1mlcev1#
单元测试,请参阅Mockito或其他模拟框架。您甚至不需要在测试类本身上添加任何注解。您需要测试方法调用,并验证与其他类的交互以及结果是否符合您的预期。
这是一个使用Mockito的单元测试的例子。很明显你会想要充实它并添加更多的测试。这将为你的代码提供覆盖,并验证前置和后置条件。这不会测试存储库代码是否正确Map或事务边界是否按预期工作,这必须使用集成测试来完成。
您的Assert逻辑不正确
您Assert同一例程具有相同余额。这将始终为真。您希望在执行方法
makeTransactionFromSenderToReceiver
之前,通过将新客户保存到存储库或获取原始余额来检查调整是否符合预期。v7pvogib2#
参与者验证者.验证参与者(参与者DTO);参与者participant=参与者DTO.准备实体(参与者DTO);