'Spring does not load Constructor with jUnit parematerised tests for each test
I use Redis keyspace notifications. In my Spring application I have below class:
@Service
public class KeyExpiredPublisher {
private final JedisPool jedisPool;
@Autowired
private KeyExpiredSubscriber keyExpiredSubscriber;
public KeyExpiredPublisher(JedisPool defaultJedisPool) {
jedisPool = defaultJedisPool;
}
@PostConstruct
public void enablePublishExpire() {
enablePublish().subscribe();
}
public Mono<Void> enablePublish() {
Mono<Void> mono = Mono.fromRunnable(() -> {
Jedis jedis = jedisPool.getResource();
String subscribedEventPattern = "__keyevent@0__:expired";
jedis.psubscribe(keyExpiredSubscriber, subscribedEventPattern);
});
return mono.subscribeOn(Schedulers.boundedElastic());
}
}
All mono stuff there is just for multithreading.
I have a parameterised unit test, which starts redis before each test and stops it after each test. However before each test, the constructors are not injected. Test with first parameter is passing because it gets to constructor (@PostConstruct method above) and subscription happens. However, after the first run, @BeforeEach kills the redis and although other tests start redis again, the code never goes into @PostSonstruct again so subscription never happens for other tests.
Is there any way to make sure Spring loads application before each parameter?
Solution 1:[1]
Depending on what you precisely do in your tests (you didn't show us), spring might be reusing the application context for performance reasons, thus only one instance of the bean is created. Usually a DirtiesContext Annotation in the test setup helps with this.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Kathrin Geilmann |
