[ACCEPTED]-How to mock SessionFactory or Session by PowerMockito in a project using Spring and Hibernate?-powermock

Accepted answer
Score: 12

Why don't do this :

@Before
public void setUp() {
    mockedSessionFactory =  Mockito.mock(SessionFactory.class);
    mockedSession = Mockito.mock(Session.class);
    mockedTransaction = Mockito.mock(Transaction.class);
    Mockito.when(mockedSessionFactory.openSession()).thenReturn(mockedSession);
    Mockito.when(mockedSession.beginTransaction()).thenReturn(mockedTransaction);
    loginDAO.setSessionFactory(this.mockedSessionFactory);
}

instead of :

@Autowired
public void setSessionFactory(SessionFactory sessionFactoryCore) {
    mockedSessionFactory =  PowerMockito.mock( sessionFactoryCore.getClass());
    mockedSession = PowerMockito.mock(Session.class);
    PowerMockito.doReturn(mockedSession).when(mockedSessionFactory).openSession();
    PowerMockito.doReturn(mockedTransaction).when(mockedSession).beginTransaction();
    loginDAO.setSessionFactory(this.mockedSessionFactory);
}

In addition, it 1 allows you to not use powermock.

Score: 1

Interesting part is here :

Caused by: java.lang.NoClassDefFoundError: org/mockito/internal/MockitoInvocationHandler
    at org.powermock.api.mockito.PowerMockito.mock(PowerMockito.java:138)
    at com.aeon.ps.dao.LoginDAOTest2.setSessionFactory(LoginDAOTest2.java:61)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:586)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:284)
    ... 26 more

It means that 15 powermock is using an internal class that 14 is not available in the mockito distribution 13 your are using.

From that information I gather 12 you are using Mockito 1.9.5-rc1, with some 11 other recent Powermock release. As of now, Johan 10 din't released a newer version of Powermock 9 that take care of the changes that were 8 made in Mockito 1.9.5-rc1.

These refactoring 7 changes in Mockito were made to help the 6 introduction of the MockMaker API, which 5 allows a third party to provide his own 4 mock factory, bytecode engine or else to 3 create mocks. See the documentation here 2 : http://docs.mockito.googlecode.com/hg/1.9.5-rc1/org/mockito/Mockito.html

So for now, you should use Mockito 1.9.0 1 if you are using Powermock.

More Related questions