Spring Boot:测试@服务类

vwkv1x7d  于 2023-01-02  发布在  Spring
关注(0)|答案(2)|浏览(139)

我对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());
    }
}
zy1mlcev

zy1mlcev1#

单元测试,请参阅Mockito或其他模拟框架。您甚至不需要在测试类本身上添加任何注解。您需要测试方法调用,并验证与其他类的交互以及结果是否符合您的预期。
这是一个使用Mockito的单元测试的例子。很明显你会想要充实它并添加更多的测试。这将为你的代码提供覆盖,并验证前置和后置条件。这不会测试存储库代码是否正确Map或事务边界是否按预期工作,这必须使用集成测试来完成。

public class TransactionServiceTest {

    @Rule
    public MockitoRule mockitoRule = MockitoJUnit.rule();

    @Mock
    private MessagingService mockMessagingService;
    @Mock
    private CustomerRepository mockCustomerRepository;

    @Test
    public void testMakeTransactionFromSenderToReceiver() {
        // setup the state of the sender and receiver
        Customer sender = new Customer();
        sender.setBalance(5.0);
        Customer receiver = new Customer();
        receiver.setBalance(10.0);
        TransactionService transactionService = new TransactionService(mockMessagingService, mockCustomerRepository);

        transactionService.makeTransactionFromSenderToReceiver(sender, receiver);

        // assert the expected state of the Customer objects
        assertEquals(1.0, sender.getBalance());
        assertEquals(1.0, receiver.getBalance());

        // verify that the repositories were called appropriately once
        // this can be made to be more specific and check the argument that was passed - see Mockito documentation
        verify(mockCustomerRepository, times(2)).save(any());
    }

}

您的Assert逻辑不正确

@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());
}

您Assert同一例程具有相同余额。这将始终为真。您希望在执行方法makeTransactionFromSenderToReceiver之前,通过将新客户保存到存储库或获取原始余额来检查调整是否符合预期。

@Test
public void testTransactionBetweenCustomersAndBalanceOfReceiver() {

    int AMOUNT = 50;

    // prepare your test data unless you always expect those values to exist.
    Customer customerReceiver = new Customer();
    customerReciever.setName("Oksana");
    customerReceiver.setBalance(12);
    customerReceiver = repository.save(customerReceiver);

    Customer customerSender = new Customer();
    customerSender.setName("Deniss");
    customerSender.setBalance(5);
    customerSender = repository.save(customerSender);

    // assign before executing method
    int expectedReceiverAmount = customerReceiver.getBalance() + AMOUNT;
    int expectedSenderAmount = customerSender.getBalance() - AMOUNT;
    transactionService.makeTransactionFromSenderToReceiver(customerSender, customerReceiver, AMOUNT);

    assertEquals(expectedSenderAmount, customerSender.getBalance());
    assertEquals(expectedReceiverAmount, customerReceiver.getBalance());
}
v7pvogib

v7pvogib2#

参与者验证者.验证参与者(参与者DTO);参与者participant=参与者DTO.准备实体(参与者DTO);

Participant participant =new Participant();
participant.setName=(participantDTO.getName());
participant.setAge=(participantDTO.getAGE());
participant.setEmailId=(participantDTO.getemailId());
participant.setContactNo=(participantDTO.getContactNo());
participant.setCouponNo=(participantDTO.getCouponNo());
participant.setWinningAmount=(participantDTO.getWinningAmount());

participant=participantRepository.save(participant);
participantDTO.setParticipantId(participant.getParticipantId());
return participantDTO

@Override
Participant participant=participantRepository..findByCouponNumber(couponNumber);
if(participant==null)
{
throw new LotteryBookingException(".....")
}
ParticipantDTO participantDTO=ParticipantDTO.prepareDTO(participant);

Participant participant =new Participant();
participant.setName=(participantDTO.getName());
participant.setAge=(participantDTO.getAGE());
participant.setEmailId=(participantDTO.getemailId());
participant.setContactNo=(participantDTO.getContactNo());
participant.setCouponNo=(participantDTO.getCouponNo());
participant.setWinningAmount=(participantDTO.getWinningAmount());

return participantDTO;

相关问题