Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EasyMock and Unitils equivalent to Mockito @ InjectMocks

Is there any techniques available in EasyMock or Unitils Mock (Not Unitils supported EasyMock) to inject the mocks directly into the Class Under Test?

For eg. in Mockito it is possible to inject mocks directly into member variables of a class,

public class TimeTrackerTest {
    @InjectMocks   // Used to create an instance the CUT
    private TimeTrackerBean cut;
    @Mock  // Used to create a Mock instance
    EntityManager em;
    @Before
    public void injectMockEntityManager() {
        MockitoAnnotations.initMocks(this);   // Injects Mocks into CUT
    }
    @Test
    ...
}

Can such things be done with EasyMock or Unitils Mock? In easymock, we need a separate setter method in the CUT to support injection from the tests. Am I right or direction injection is somehow possible?

-Thanks

like image 587
Bala Avatar asked Feb 06 '12 12:02

Bala


3 Answers

Maybe this thread has gone dead but yes you can now do this using EasyMock 3.2 with the tags @TestSubject, @Mock and running the test with @RunWith(EasyMockRunner.class). See this well written (not by me!) example:

http://henritremblay.blogspot.ie/2013/07/easymock-32-is-out.html

like image 153
user2298491 Avatar answered Oct 16 '22 10:10

user2298491


I don't know of any annotations that would let you do this with EasyMock, however, Spring has ReflectionTestUtils which will let you easily do injection to private fields without requiring a setter method. Before I switched to Mockito, I found this class invaluable.

like image 27
jhericks Avatar answered Oct 16 '22 08:10

jhericks


Unitils has the "Inject" module for injection of mock objects into tested objects. See http://unitils.org/tutorial-inject.html for details.

For example:

public class MyServiceTest extends UnitilsJUnit4
{ 
    @TestedObject MyService myService; 
    @InjectIntoByType Mock<MyDao> myDao; 

    @Test
    public void myTestMethod()
    {
        myDao.returns("something").getSomething(); 

        myService.doService();

        myDao.assertInvoked().storeSomething("something"); 
    }
}
like image 43
Rogério Avatar answered Oct 16 '22 09:10

Rogério