1

I have problem with unit test. Below is the sample code snippet. I have mock a bean and inject into @configuration class and use the mocked property to create another bean.

In the below, if i inspect, b.getSomething() returning me the default value like "" for string, 0 for int. etc. I am not getting the mocked value. Any idea how to do?

@Configuration
class A{

  @Autowired B b;

  @Bean
  public SomeClass someBean(){

   SomeClass clas = new SomeClass();
   clas.setSomething(b.getSomething());
   return clas;
   }

 }



 @ContextConfiguration(classes = { A.class}, loader = SpringockitoAnnotatedContextLoader.class)
class ATest{

@ReplaceWithMock
@Autowired
B b;

@Before
public void setup(){
Mockito.when(b.getSomething()).thenReturn("ABC");
}

}
Manoj
  • 5,707
  • 19
  • 56
  • 86
  • 1
    Always ask yourself in such situation: Do you really need Spring in doing such unit test. For example, in the example in your test, you can (and you should) explicitly instantiate the class you wanna test and inject the mocks, instead of relying on Spring to do it – Adrian Shum Nov 23 '15 at 03:19
  • If you think you really really need spring in your unit test, this question may give you some idea on (one of) the ways to do so: http://stackoverflow.com/q/10906945/395202 – Adrian Shum Nov 23 '15 at 03:20

1 Answers1

2

This is the way I create my mocks. Have a Bean which returns the Mock, and autowire it where needed.

@Autowired
MyClass myClassMock;

@Bean
public MyClass getMyClassMock(){
    MyClass mock = Mockito.mock(MyClass.class);
    Mockito.when(mock.getSomething()).thenReturn("ABC");
    return mock;
}
Guillaume F.
  • 5,905
  • 2
  • 31
  • 59