awahaani
awahaani

Reputation: 143

Why can't a set a mockito mock to a field of a autowired initialized spring bean?

Naively I thought I could set a mockito to un already initialized spring bean. When I do that somewhere along the way the bean is getting back the original spring injected value.

Is there no other way than injecting the mock thru xml or java spring config?

Thanks

Upvotes: 1

Views: 734

Answers (1)

Alexander
Alexander

Reputation: 2898

I assume you are talking about integration tests that you run e.g. with '@RunWith(SpringJUnit4ClassRunner.class)'. In unit tests you would not usually deal with Spring - this is the advantage of Spring and DI.

I usually override the production configuration with test configuration using the following:

  • To override @Autowired/@Injected bean, mark your beans in the test configurations as @Primary
  • To override beans injection by name, use aliases in your test configuration (see an example below)

Your production config:

@Configuration
class ProdConfig {
     @Bean Abc abc() { return new AbcImpl(); }
     @Bean Xyz xyz() { return new XyzImpl(); }
}
class SomeBean {
    @Inject Abc abc;
    @Resource(name="xyz") Xyz xys;
}

Your test config:

@Configuration
@Import(ProdConfig.class)
class TestConfig {
     @Primary
     @Bean(name={"abcOverride", "abc"}) 
     Abc abc() { 
        return Mockito.mock(Abc.class); 
     }
     @Primary
     @Bean(name={"xyzOverride", "xyz"}) 
     Xyz xyz() { 
        return Mockito.mock(Xyz.class); 
     }
}

And then in your test:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = TestConfig.class)
@TestPropertySource(properties = {"some.prop=true"}) //you can override properties as well
class MyTest {...}

One more thing: you might need to explicitly exclude your TestConfig classes to avoid interfering with other integration tests:

@Configuration
@ComponentScan(basePackages={"com.your.code"}, 
    excludeFilters = {@ComponentScan.Filter(pattern = ".*TestConfig.*")}) 
class ProdConfig {...}

Upvotes: 1

Related Questions