dwjohnston
dwjohnston

Reputation: 11890

How can I set Mockito `when` method when instantiating mock objects in Spring?

The method described in this answer best suits me for instantiating my mock objects.

<bean id="dao" class="org.mockito.Mockito" factory-method="mock"> 
    <constructor-arg value="com.package.Dao" /> 
</bean> 

However, I also need to set the Mockito when method(s).

Can I do that in the XML, or is the only way to to it like:

when( objectToBestTested.getMockedObject()
     .someMethod(anyInt())
    ).thenReturn("helloWorld");

within my test case?

The reason I ask, is because I don't otherwise need a getter for MockedObject, and I'd only be adding a getter so I can test ObjectToBeTested.

Upvotes: 0

Views: 920

Answers (1)

Koitoer
Koitoer

Reputation: 19533

This is the way of how I use Mockito with Spring.

Lets assume I have a Controller that use a Service and this services inject its own DAO, basically have this code structure.

@Controller
public class MyController{
  @Autowired
  MyService service;
}

@Service
public class MyService{
  @Autowired
  MyRepo myRepo;

  public MyReturnObject myMethod(Arg1 arg){
     myRepo.getData(arg);
  }
}

@Repository
public class MyRepo{}

Code below is for the junit test case

@RunWith(MockitoJUnitRunner.class)
public class MyServiceTest{

    @InjectMocks
    private MyService myService;

    @Mock
    private MyRepo myRepo;

    @Test
    public void testMyMethod(){
      Mockito.when(myRepo.getData(Mockito.anyObject()).thenReturn(new MyReturnObject());
      myService.myMethod(new Arg1());
    }
}

If you are using standalone applications consider mock as below.

@RunWith(MockitoJUnitRunner.class)
public class PriceChangeRequestThreadFactoryTest {

@Mock
private ApplicationContext context;

@SuppressWarnings("unchecked")
@Test
public void testGetPriceChangeRequestThread() {
    final MyClass myClass =  Mockito.mock(MyClass.class);
    Mockito.when(myClass.myMethod()).thenReturn(new ReturnValue());
    Mockito.when(context.getBean(Matchers.anyString(), Matchers.any(Class.class))).thenReturn(myClass);

    }
}

I dont really like create mock bean within the application context, but if you do make it only available for your unit testing.

Upvotes: 4

Related Questions