0

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.

Community
  • 1
  • 1
dwjohnston
  • 11,163
  • 32
  • 99
  • 194

1 Answers1

4

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.

Koitoer
  • 18,778
  • 7
  • 63
  • 86
  • Cheers, thanks for you answer. Would you mind taking a look at a couple of other related questions I had re: unit testing and spring? Particularly this one: http://stackoverflow.com/questions/29203218/instantiating-objects-when-using-spring-for-testing-vs-production – dwjohnston Mar 25 '15 at 03:04