简体   繁体   中英

How to replace bean in BeanFactory with own mock in Spring Boot?

To implement the factory in a project, I use a Spring's BeanFactory . Therefore, the extraction of the required provider is as follows:

@Override
    public T getInstance(String key) {
        // ...
        return beanFactory.getBean(registry.get(key));
}

Thus, I can extract providers as follows:

amazingProviderFactory.getInstance("some key");

It works fine. But for tests, it is necessary to extract a provider from the BeanFactory and replace it with own mocked-implementation.

The following method can solve the problem, but this is only an example found on the Internet, and it's not quite clear how to implement it correctly:

Mockito.when(SpringContext.getBean("some key")).thenReturn(mockedProvider);

What are the right ways to accomplish the problem?

Thanks!

Just thinking about :

But for tests, it is necessary to extract a provider from the BeanFactory and replace it with own mocked-implementation.

Why would you do it ? Rather you would write a separate unit test for each of the provider and mock any IO operation as required. You could also have a separate minimal test for your own implemented BeanFactory which test out getInstance method.

Still if you want to do this then something like this :

@RunWith(SpringRunner.class)
@SpringBootTest
public class ProviderTest {

    @MockBean
    private ProviderA providerA;

    @MockBean
    private ProviderB providerB;
}

Now amazingProviderFactory.getInstance("some key"); should return mocked bean as declard above.

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM