Search code examples
springunit-testingspring-webfluxreactor

How to test a reactive method within Rest Controller called from service


The following is my rest controller code 

    @RequestMapping(produces = MediaType.TEXT_EVENT_STREAM_VALUE, value = "/myMethod")
        public Flux<Integer> myMethod() {       
            return service.myServiceMethod();
        }


My service method is   

      public Flux<Integer> myServiceMethod() {
                return Flux.fromStream(Stream.generate(() -> no++).map(s -> Integer.valueOf(s))).delayElements(Duration.ofSeconds(5));
            }

I am trying to write a test as below but it is not working

@Autowired
    NumberEventService serv; 

@Test
    public void test() {
      StepVerifier.withVirtualTime(() -> 
            Flux.just(serv.generateNumberEvent()).delayElements(Duration.ofSeconds(5)))
            .expectSubscription() //t == 0  
            .expectNoEvent(Duration.ofSeconds(1))   
            .expectNextCount(1) 
            .expectNoEvent(Duration.ofSeconds(1))
            .expectNextCount(1) 
            .expectNoEvent(Duration.ofSeconds(1))
            .expectNextCount(1) 
            .expectComplete()   
            .verify();
    }

I get an error as

java.lang.BootstrapMethodError: java.lang.NoClassDefFoundError: reactor/core/scheduler/TimedScheduler
    at reactor.test.StepVerifier.withVirtualTime(StepVerifier.java:167)
    at reactor.test.StepVerifier.withVirtualTime(StepVerifier.java:140)

I launched the app in the port 8080 and ran the test. What is the mistake I am doing?

I will launch this method in 8080 and a client in the port 8082 will consume the event.

How can this be unit tested?


Solution

  • You will encounter a NoClassDefFoundError when reactor-core versions do not match between what spring-starter-reactor brings and the reactor-test addons.

    You have to look at your spring-boot-starter-webflux dependencies, and search the version of the reactor-core module.

    Then you'll be able to add the correct version of the reactor-test module.

    In my example, the current version of the reactor-core module is 3.1.8.RELEASE, so I have to add the same version of the reactor-test module.

    You can check the maven repository of the reactor test support here

    enter image description here