Skip to content

Instantly share code, notes, and snippets.

@thomasdarimont
Last active August 29, 2015 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thomasdarimont/0114979d6ac99a7414d2 to your computer and use it in GitHub Desktop.
Save thomasdarimont/0114979d6ac99a7414d2 to your computer and use it in GitHub Desktop.
How to overwrite nested dependencies for an integration test.
package demo.business;
public interface BusinessService {
void businessMethod();
}
package demo.business;
import org.springframework.beans.factory.annotation.Autowired;
public class DefaultBusinessService implements BusinessService {
private final Dependency dependency;
@Autowired
public DefaultBusinessService(Dependency dependency) {
this.dependency = dependency;
}
@Override
public void businessMethod() {
System.out.println(dependency);
}
}
package demo.business;
public interface Dependency {}
package demo.business;
public class DefaultDependency implements Dependency{}
package demo.business;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class BusinessConfig {
@Bean
public BusinessService businessService(Dependency dependency) {
return new DefaultBusinessService(dependency);
}
@Bean
public Dependency dependency() {
return new DefaultDependency();
}
}
package demo.business;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@ContextConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
public class BusinessServiceIT {
@Autowired BusinessService businessService;
@Import(BusinessConfig.class)
@Configuration
static class Config{
//@Bean @Primary //uncomment the bean definition to get the "mock" dependency wired into the DefaultBusinessService
public Dependency dependency(){
return new Dependency() {};
}
}
@Test
public void test() {
businessService.businessMethod();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment