I need to use Redis in a service. I’m following https://quarkus.io/guides/redis-reference and so I have created the following service:
@ApplicationScoped
public class MyService {
private final ReactiveValueCommands<String, String> commands;
public MyService(ReactiveRedisDataSource redis) {
commands = redis.value(String.class, String.class);
}
public String getString() {
return "string";
}
}
Now, I’m trying to test it with the following:
@QuarkusTest
class MyServiceTest {
@InjectMock
ReactiveRedisDataSource redis;
@Inject
MyService myService;
@Mock
private ReactiveValueCommands<String, String> commands;
private AutoCloseable mocks;
@BeforeEach
void setUp() {
mocks = MockitoAnnotations.openMocks(this);
when(redis.value(String.class, String.class)).thenReturn(commands);
}
@AfterEach
void afterEach() throws Exception {
mocks.close();
}
@Test
void getStringShouldReturnString() {
assertEquals("string", myService.getString());
}
}
Well, the problem with this test is that MyService
‘s constructor is invoked before MyServiceTest#setUp
method, which results in MyService#commands
being null instead of being assigned MyServiceTest#commands
. Is there a way to prevent this behaviour?