【问题标题】:How to test update methods?如何测试更新方法?
【发布时间】:2022-01-06 11:21:16
【问题描述】:

我是单元测试新手,在我的 Java (Spring Boot) 应用程序中使用 JUnit。我有时需要测试更新方法,但是当我在网上搜索时,没有合适的示例或建议。那么,您能否澄清一下如何测试以下更新方法?我认为这可能需要与测试 void 不同的方法。我还认为,在测试时首先模拟记录,然后更新其字段,然后更新。最后再次检索记录并比较更新的属性。但我认为可能有比这个没有经验的方法更合适的方法。

public PriceDTO update(UUID priceUuid, PriceRequest request) {
    Price price = priceRepository
                    .findByUuid(priceUuid)
                    .orElseThrow(() -> new EntityNotFoundException(PRICE));

    mapRequestToEntity(request, price);
    Price updated = priceRepository.saveAndFlush(price);
    
    return new PriceDTO(updated);
}

private void mapRequestToEntity(PriceRequest request, Price entity) {
    entity.setPriceAmount(request.getPriceAmount());
    // set other props
}

【问题讨论】:

  • 有没有人从来没有为更新方法写过单元测试?
  • 哪段代码实际上在做实体的更新?
  • priceRepository.saveAndFlush(price);amigo.
  • 那是更新数据库,不过我说的是price,应该按照request更新吧?这是在哪里完成的?
  • mapRequestToEntity(request, price);

标签: java spring-boot unit-testing junit mockito


【解决方案1】:

您需要按照以下方式做一些事情:

public class ServiceTest {

    @Mock
    private PriceRepository priceRepository;

    (...)

    @Test
    public void shouldUpdatePrice() throws Exception {
        // Arrange
        UUID priceUuid = // build the Price UUID
        PriceRequest priceUpdateRequest = // build the Price update request
        Price originalPrice = // build the original Price  
        doReturn(originalPrice).when(this.priceRepository).findByUuid(isA(UUID.class));
        doAnswer(AdditionalAnswers.returnsFirstArg()).when(this.priceRepository).saveAndFlush(isA(Price.class));

        // Act
        PriceDTO updatedPrice = this.service.update(priceUuid, priceUpdateRequest);

        // Assert
        // here you need to assert that updatedPrice is as you expect according to originalPrice and priceUpdateRequest
    }
}

【讨论】:

  • 非常感谢,但我不知道它是如何工作的。您能否解释一下doReturn、doAnswer 和PriceDTO updatedPrice = ... 行的工作原理?
  • doReturn 和 doAnswer 是基本的 Mockito 方法,它们设置在实际方法中调用时在 when 子句中定义的调用将返回的内容。 PriceDTO updatedPrice = ... 行只是对服务update() 方法的调用(service 应该是具有您要测试的类的实例的属性)。如果您习惯编写单元测试,那么您应该熟悉所有这些内容。
  • 大部分我都知道,但看不懂doAnswer(AdditionalAnswers.returnsFirstArg()).when(this.priceRepository).saveAndFlush(isA(Price.class)); 。你能澄清一下吗?
  • 这将基本上返回传递给priceRepository.saveAndFlush() 方法的第一个参数,实际上再现了在成功情况下调用真实方法将返回的内容。
  • 非常感谢朋友
【解决方案2】:

您需要模拟类对象priceRepository 的行为。 因此,您必须编写如下内容才能开始:

// priceRepository should be mocked in the test class
Mockito.when(priceRepository.findByUuid(any(UUID.class))).thenReturn(new Price());

【讨论】:

  • 非常感谢,但剩下的呢?能否请您发布一个示例测试方法?
  • 没有看到实际的实现,很难评论。对于 void 方法,您需要使用doNothing() 方法来模拟行为。
  • 不,我不是那个意思。我只是说如果我应该调用服务的findByUuid 方法,然后填充返回实体的属性。您能否在示例中包含这些部分?
  • 朋友?有回复吗?
【解决方案3】:

因此,如果您的唯一目的是验证您是否调用了 save,那么您可能正在寻找类似这样的内容:

@ExtendWith(MockitoExtension.class)
public class ServiceTest {
    @Mock
    private PriceRepository priceRepository;
    @InjectMocks
    private Service service;

    @Test
    public void update() throws Exception {
        // Given
        Price price = new Price();
        price.setUid(UUID.randomUUID());
        price.setPriceAmount(100);

        when(priceRepository.findByUid(price.getUid()))
            .thenReturn(price);

        ArgumentCaptor<Price> priceArgument =                      
            ArgumentCaptor.forClass(Price.class);

        when(incidentRepository.saveAndFlush(priceArgument.capture()))
            .thenAnswer(iom -> iom.getArgument(0));


        // When
        PriceRequest priceRequest = new PriceRequest();
        priceRequest.setPriceAmount(123);

        PriceDTO updatedPrice = this.service.update(price.getUid(), priceUpdateRequest);

        // Then
        assertThat(priceArgument.getValue().getPriceAmount())
            .isEqualTo(123);
    }
}

【讨论】:

  • 非常感谢您的详细回答,但据我所知,您可以在 this 页面上看到,没有必要使用 ArgumentCaptor,因为 Update 方法返回 DTO(我已经可以达到返回值)。那么,有什么想法吗?
  • 参数捕获非常有意义,因为它是您传递给 save 方法的实际值。其他所有值,例如返回的与您传递给 save 方法的不同
猜你喜欢
  • 1970-01-01
  • 2011-09-13
  • 1970-01-01
  • 2019-07-19
  • 1970-01-01
  • 1970-01-01
  • 2012-03-01
  • 2023-03-22
  • 2021-10-29
相关资源
最近更新 更多