Spring WebFlux: block() method return null in Spring Data Reactive MongoDB

3.6k Views Asked by At

i'm trying to learn project Reactor and have the problem.

@Test
@DisplayName("check that standaloneUser fields are correct")
void validateUserFields() {
    userService.save(standaloneUser).subscribe();
    assertEquals(userService.count().block(), Long.valueOf(1));
    User user = userService.findByEmail("[email protected]").block();
    assertNotNull(user);
    assertNotNull(user.getId());
    assertEquals(user.getFirstName(), "test");
    assertEquals(user.getLastName(), "test");
    assertNotEquals(user.getPassword(), "test");
    assertEquals(user.getRole(), Role.CANDIDATE);
    assertNotNull(user.getCreatedDate());
    assertNull(user.getStoppedDate());
    assertEquals(user.getEmail(), "[email protected]");
}

Sometimes block() method returns null. Who can explain me this? Thanks

1

There are 1 best solutions below

0
On BEST ANSWER

block() can return null, it means the Mono completed empty, which in this case means the user wasn't found.

Could it be that it wasn't properly saved? (although you assert the user count)

Note that you do userService.save(standaloneUser).subscribe(). This form is often not ideal, as it is "async fire-and-forget":

  • async -> it might complete after the subsequent asserts
  • fire and forget -> no error handler means that it could terminate with an error and hide it from you.

Make an habit of at least setting onNext and onError handler lambdas when calling subscribe.