【问题标题】:Spring boot reactor test how to log and check test of Flux<String> with StepVerifier contains stringSpring Boot reactor 测试如何使用 StepVerifier 记录和检查 Flux<String> 的测试包含字符串
【发布时间】:2021-02-24 15:48:11
【问题描述】:

我有一个 Spring Boot 测试,其代码创建了一个简单的 Flux&lt;String 异步结果。我想测试是否有一个包含字符串price 的结果。代码是这样的:

@SpringBootTest
@ContextConfiguration(classes = PriceTests.class)
public class PriceTests {

@Autowired
RestController controller;

    @Test
    public void DoPriceTests() throws InterruptedException
    {
        Flux<String> prices = controller.getPrices();

        Logs.Info("Test prices");  

        StepVerifier.create(prices)
        .expectNextMatches(s -> s.contains("price"))
        .expectComplete()
        .verify(Duration.ofSeconds(3));
    }
}

问题是我注意到当没有价格时,测试仍然通过!那不应该发生。我怎样才能log expectNextMatches 字符串?例如,类似这样的内容将显示每个价格的Flux&lt;String&gt; 的实际值是多少:

StepVerifier.create(prices)
  .expectNextMatches(s -> {
      Logs.Info(s);
      s.contains("price");
  })
  .expectComplete()
  .verify(Duration.ofSeconds(3));

【问题讨论】:

  • 空通量不是错误,不应被视为错误。如果你想让它失败,你需要 controller.getPrices() 在空时返回一个错误。
  • 空通量不包含字符串“price”,正如 expectNextMatches 测试谓词所期望的那样?
  • StepVerifier.create(Flux.empty()).expectNextMatches(s -&gt; s.equals("hello")).expectComplete().verify(Duration.ofSeconds(3)); 此代码按预期失败。是不是你的生产代码有问题?

标签: java spring-webflux project-reactor reactor


【解决方案1】:

最后一些答案,要么使用blockfirstStepVerifier 订阅Flux,然后在String 数据上使用常规Hamcrest 断言。在测试结束前给出 3 秒的超时时间。

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.CoreMatchers.containsString;
// Other imports

@SpringBootTest
@ContextConfiguration(classes = PriceTests.class)
public class PriceTests {

@Autowired
RestController controller;

@Test
public void UseBlock() throws InterruptedException
{
    Flux<String> prices = controller.getPrices();

    Logs.Info("Test prices");  

    // Using block
    String myPrice = prices.blockFirst(Duration.ofSeconds(3));        
    Logs.Info(myPrice);
    assertThat(myPrice, containsString("price"));
}

@Test
public void UseStepVerifier() throws InterruptedException
{
    Flux<String> prices = controller.getPrices();

    Logs.Info("Test prices");  

    // Using StepVerifier
    StepVerifier.create(prices)
        .assertNext(s -> 
        {
            Logs.Info(s);
            assertThat(s, containsString("price"));
        })
        .thenCancel()
        .verify(Duration.ofSeconds(3));
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-26
    • 1970-01-01
    • 2017-12-29
    • 2016-10-28
    • 2022-01-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多