0

I am new to mock testing and was wondering how I would go about mocking the following with mockito.

uDAO = (UserDAO) dao;

where dao is defined as

protected DAO<T, Long> dao;

Thanks!

  • Problem is: if something is inherited, than you will have a hard time mocking it. The real solution there is to use dependency injection to ensure that you can provide a matching object to your superclass at some oint. – GhostCat Aug 08 '16 at 19:14
  • how do you get to initialize 'dao' ? – kuhajeyan Aug 09 '16 at 10:52

1 Answers1

1

To inject mocks for private and protected fields (which do not have a public setter method) you have to use reflections. Using reflections you can set a mocked object in place of that protected field. Below is a sample of relections code.

Field hack = <PUT YOU CLASS NAME>.class.getDeclaredField("dao");
hack.setAccessible(true);
hack.set(<Object of the class where you are injecting the mock>,<the mock object>);

To create the mocked object you can use the regular PowerMockito.mock or Mockito.mock functions.

For more info on reflections have a look at the below links:

Is it possible in Java to access private fields via reflection http://www.java2s.com/Code/Java/Reflection/Setprivatefieldvalue.htm

Community
  • 1
  • 1
Spandan Thakur
  • 338
  • 2
  • 14