Testing a generic function with function as a paremeter

100 Views Asked by At
AuthenticationService.java
public <T> Mono<T> withUser(Function<User, Mono<T>> function){
    return Mono.deferContextual(ctx -> {
        User user = ctx.get(User.class);
        function.apply(user);
    })
}

Then I have a separate client using this

UserService.java
public Mono<Boolean> doSomethingMeaningfulWithUser(){
    authenticationService.withUser(user -> {
        ... 
    }
}

In my test I would have

@Mock
private AuthenticationService authService;

private UserService userService = new UserService(authService);

@Test
public void testMeaningfulStuff(){
   ...when(...)
   ...userService.doSomethingMeaningfulWithUser()
}

Is there an idiomatic way to setup a @Mock with AuthenticationService here, so that I can test the business logic with User in doSomethingMeaningfulWithUser, or is it easier to wire AuthenticationService fully in this case here?

1

There are 1 best solutions below

1
rilent On

I would mock it like that :

@Test
public void testMeaningfulStuff() {
  User user = new User();
  Mono<User> userMono = Mono.just(user);
  
  when(authService.withUser(any())).thenReturn(userMono);

  userService.doSomethingMeaningfulWithUser().subscribe(result -> {
     //test stuffs
  });
}

This way, you can test the business logic in doSomethingMeaningfulWithUser without having to wire up the full AuthenticationService implementation.