0
votes

Sample Code

Class Which is to be Mocked

@Transactional(propagation=Propagation.REQUIRED, rollbackFor=RuntimeException.class)
@Repository
public class Sample {
    @Autowired
    SessionFactory sessionFactory;

    public Pdt loadpdtType(String planName) 
    {           
       Pdt pdt=new Pdt();

       System.out.println("I am called");
       Session session = sessionFactory.getCurrentSession();
       Query query = session.createQuery("From Dmaster where planName=:planName order by id")
                .setParameter("planName", planName);
       pList = query.list();

       pdt.setSI(pList.get(0).getSI());

       if(planName.equalsIgnoreCase("ABCD")
           pdt.setPDTType("xyz");
       else
           pdt.setPDTType("1234");
       return pdt;
   }

   public Resp getSeq(String Id,String type){
      Resp r=new Resp(Id,type);   
      return r;
   }

}

I need to call getpdtType() and getSeq() method from junit. My test Method is as follows

class SampleTester {

    @Autowired
    Sample samp;

    Pdt pdt;

    @Test
    public void Testt()     {
        try {
            samp=Mockito.mock(Sample.class);                
            Mockito.when(samp.loadpdtType("sampletext").thenCallRealMethod();
            pdt=samp.loadpdtType("sampletext");         
            Mockito.verify(samp).loadpdtType("sampletext");
            System.out.println("testresult:"+pdt.getPDTType());
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
}

And The output is

I am called

java.lang.NullPointerException at com.docs.Sample.loadpdtType(Sample.java:58) [classes/:?] at com.docs.Sample$$EnhancerByMockitoWithCGLIB$$f5b2927b.CGLIB$loadpdtType$0() [mockito-core-1.10.19.jar:?] at com.docs.Sample.$$EnhancerByMockitoWithCGLIB$$f5b2927b$$FastClassByMockitoWithCGLIB$$15d15c8c.invoke() [mockito-core-1.10.19.jar:?] at org.mockito.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:216) [mockito-core-1.10.19.jar:?] at org.mockito.internal.creation.cglib.DelegatingMockitoMethodProxy.invokeSuper(DelegatingMockitoMethodProxy.java:19) [mockito-core-1.10.19.jar:?] at org.mockito.internal.invocation.realmethod.DefaultRealMethod.invoke(DefaultRealMethod.java:21) [mockito-core-1.10.19.jar:?] at org.mockito.internal.invocation.realmethod.CleanTraceRealMethod.invoke(CleanTraceRealMethod.java:30) [mockito-core-1.10.19.jar:?] at org.mockito.internal.invocation.InvocationImpl.callRealMethod(InvocationImpl.java:112) [mockito-core-1.10.19.jar:?] at org.mockito.internal.stubbing.answers.CallsRealMethods.answer(CallsRealMethods.java:41) [mockito-core-1.10.19.jar:?] at org.mockito.internal.stubbing.StubbedInvocationMatcher.answer(StubbedInvocationMatcher.java:34) [mockito-core-1.10.19.jar:?] at org.mockito.internal.handler.MockHandlerImpl.handle(MockHandlerImpl.java:91) [mockito-core-1.10.19.jar:?] at org.mockito.internal.handler.NullResultGuardian.handle(NullResultGuardian.java:29) [mockito-core-1.10.19.jar:?] at org.mockito.internal.handler.InvocationNotifierHandler.handle(InvocationNotifierHandler.java:38) [mockito-core-1.10.19.jar:?] at org.mockito.internal.creation.cglib.MethodInterceptorFilter.intercept(MethodInterceptorFilter.java:59) [mockito-core-1.10.19.jar:?] at com.docs.Sample$$EnhancerByMockitoWithCGLIB$$f5b2927b.loadpdtType() [mockito-core-1.10.19.jar:?] at com.documentation.SampleTester.Testt(SampleTester.java:31) [test-classes/:?] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.8.0_91] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[?:1.8.0_91] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:1.8.0_91] at java.lang.reflect.Method.invoke(Method.java:498) ~[?:1.8.0_91] at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50) [junit-4.12.jar:4.12] at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) [junit-4.12.jar:4.12] at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47) [junit-4.12.jar:4.12] at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) [junit-4.12.jar:4.12] at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325) [junit-4.12.jar:4.12] at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78) [junit-4.12.jar:4.12] at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57) [junit-4.12.jar:4.12] at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) [junit-4.12.jar:4.12] at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) [junit-4.12.jar:4.12] at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) [junit-4.12.jar:4.12] at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) [junit-4.12.jar:4.12] at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) [junit-4.12.jar:4.12] at org.junit.runners.ParentRunner.run(ParentRunner.java:363) [junit-4.12.jar:4.12] at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50) [.cp/:?] at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) [.cp/:?] at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459) [.cp/:?] at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675) [.cp/:?] at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382) [.cp/:?] at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192) [.cp/:?]

2
please add the stacktrace and mark the line where the exception occur - Jens
And format your code. The editor has a preview. - chrylis -cautiouslyoptimistic-
samp=Mockito.mock(Sample.class); so why would the sessionFactory in samp be non null??? - user180100

2 Answers

0
votes

Multiple things here.

  1. You don't need the below line:

    Mockito.when(samp.loadpdtType("sampletext").thenCallRealMethod();

    because you are testing the class Sample so it will obviously call the loadpdtType method.

  2. You need to set the mock for SessionFactory in Sample class and mock all the method which are being called on sessionFactory in loadpdtType.

You need something like below:

class SampleTester {

@Mock SessionFactory mockSessionFactory;
@Mock Session mockSession;

@InjectMock
Sample samp;

Pdt pdt;

@Test
public void Testt()     {
    try {
        samp=Mockito.mock(Sample.class);                

        pdt=samp.loadpdtType("sampletext");   
        when(mockSessionFactory. getCurrentSession()).thenReturn(mockSession); 
// mock other method which are called on Session 

        Mockito.verify(samp).loadpdtType("sampletext");
        System.out.println("testresult:"+pdt.getPDTType());
    } catch(Exception e) {
        e.printStackTrace();
    }
  }
}
0
votes

Hurrah !! Thanks Everyone I got solution to my own question. I was making it more difficult and hard. Configured sessionfactory bean and embeddedWebApplicationContext in MyApp.class and it worked...

@RunWith(SpringJUnit4ClassRunner.class)

@SpringApplicationConfiguration(classes = MyApp.class)

@WebAppConfiguration

@IntegrationTest("server.port:0")

public class SampleTester

{
@Autowired

Sample samp;

@Test
public void Testt()     
{           
    Pdt pdt=samp.loadpdtType("sampletext"); 
    Resp r=samp.getSeq("ABC","XYZ"); 
// All assertions for Pdt, Resp follows

}

}