I have a @Service
bean that I need static
access to:
@Service
public class MyBean implements InitializingBean {
private static MyBean instance;
@Override
public void afterPropertiesSet() throws Exception {
instance = this;
}
public static MyBean get() {
return instance;
}
public String someMethod(String param) {
return "some";
}
}
Usage:
@Service
public class OtherService {
public static void makeUse() {
MyBean myBean = MyBean.get();
}
}
Problem: when I write an integration junit
test for OtherService
that makes use of the stat MyBean
access, the instance
variable is always null.
@RunWith(SpringRunner.class)
@SpringBootTest
public class ITest {
@Autowired
private OtherService service;
@MockBean
private MyBean myBean;
@Before
public void mock() {
Mockito.when(myBean.someMethod(any()).thenReturn("testvalue");
}
@Test
public void test() {
service.makeUse(); //NullPointerException, as instance is null in MyBean
}
}
Question: how can I write an integration test when using such type of static access to a spring-managed bean?