How to override one bean defined in application context

I have a web application that accesses an external web service. I am writing an automated acceptance test suite for a web application. I do not want to refer to an external web service, since it has serious overhead, I want to mock this web service. How can this happen without changing the application context of the web application? We recently switched to Spring 3.1, so I was tempted to use the new environment features. Does the new feature help me redefine this single web service and leave the application context as it is?

+6
source share
2 answers

I would use the Spring @Profile function, which I assume is the "environment" that you talked about.

For instance:

@Service @Profile("dev") public class FakeWebService implements WebService { } @Service @Profile("production") public class ExternalWebService implements WebService { } 

EDIT

And indicate which profile to use in your test:

 @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("/app-config.xml") @ActiveProfiles("dev") public class MyAcceptanceTest { } 

See this section of the Spring docs for more details.

There are several ways to set an active profile during production, but the method I used earlier is in the web.xml file:

 <servlet> <servlet-name>dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>spring.profiles.active</param-name> <param-value>production</param-value> </init-param> </servlet> 
+9
source

I would use a BeanFactoryPostProcessor , which was only registered in test scripts that you would like to make fun of.

BeanFactoryPostProcessor allows BeanFactoryPostProcessor to change the context of the application immediately after its creation and filling. You can find the name of your particular bean and register a bean for it.

 public class SystemTestBeanFactoryPostProcessor implements BeanFactoryPostProcessor { @Override public void postProcessBeanFactory(final ConfigurableListableBeanFactory factory) throws BeansException { final MyInterface myInterface = new MyInterfaceStub(); factory.registerSingleton("myInterfaceBeanName", myInterface); } } 

This will allow you to overwrite only the beans you want to mute / mock.

I'm not sure if this is the β€œnewest 3.x” way to do this. But it is very simple and easy to implement.

+4
source

Source: https://habr.com/ru/post/909764/


All Articles