在您订阅前,如何测试什么都不会发生

时间:2018-07-31 12:00:26

标签: project-reactor

return Mono.just(key) //
            .map(Service1::doSomething) //
            .map(Service2:: doSomething) //
            .map(Service3::getBytes);

我的代码如上所述,我在服务方法(Service1,Service2和Service3)中有很多日志,因此我可以确认未调用这些方法,直到通过手动验证日志文件来调用subscription方法为止。是否有任何测试工具可以帮助我自动化该测试?

1 个答案:

答案 0 :(得分:0)

Mokito可以使用模拟/间谍来跟踪调用。这是使用Spring的示例:

import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.mock.mockito.SpyBean;
import org.springframework.test.context.junit4.SpringRunner;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;

@RunWith(SpringRunner.class)
public class ExampleTests {

  @SpyBean
  private Service1 service1;

  @SpyBean
  private Service2 service2;

  @SpyBean
  private Service3 service3;

  @Test
  public void verifyNothingHappensWithoutSubscribe() {

    Mono.just("key")
        .map(service1::doSomething)
        .map(service2::doSomething)
        .map(service3::getBytes);

    verify(service1, times(0)).doSomething("key");
    verify(service2, times(0)).doSomething("key");
    verify(service3, times(0)).getBytes("key");

  }

  @Test
  public void verifyCallsWhenSubscribed() {

    Mono<byte[]> testMono = Mono.just("key")
        .map(service1::doSomething)
        .map(service2::doSomething)
        .map(service3::getBytes);

    StepVerifier.create(testMono)
        .expectNextCount(1)
        .verifyComplete();

    verify(service1, times(1)).doSomething("key");
    verify(service2, times(1)).doSomething("key");
    verify(service3, times(1)).getBytes("key");

  }

}