10

I am working on Junits with Mockito + PowerMock + PowerRule

Refer my Previous question: Getting javassist not found with PowerMock and PowerRule in Junit with Mockito

Now that I have got my Junits working successfully, I am getting a strange problem that the Eclipse debugger is not working ie I donot stop on the breakpoints although my tests are getting executed (checked with SOP statements)

Now when I remove PowerRule from Junits, The debugger starts working again

I don't know why is this happening. Please let me know if you have any idea on this

Thanks

Community
  • 1
  • 1
Bhuvan
  • 2,209
  • 11
  • 33
  • 46

2 Answers2

4

If you have used annotation @PrepareForTest({ClassName.class}) at the class level, then issue would have been occurred. One work around is to declare that annotation at method.It would allow you to debug it even though power mocking is used in your test case.

027
  • 1,553
  • 13
  • 23
1

Don't use mockStatic in this case, you will mock the whole static class, and that's why you won't be able to debug it.

Instead use one of these to avoid mocking the whole static class:

  • spy

    PowerMockito.spy(CasSessionUtil.class) PowerMockito.when(CasSessionUtil.getCarrierId()).thenReturn(1L);

  • Or stub

    PowerMockito.stub(PowerMockito.method(CasSessionUtil.class, "getCarrierId")).toReturn(1L);

  • And with stub, if the method have parameters (e.g. String, and boolean), do the below:

    PowerMockito.stub(PowerMockito.method(CasSessionUtil.class, "methodName", String.class, Boolean.class)).toReturn(1L);

And this is the finla code, I choose to use stub:

@RunWith(PowerMockRunner.class) // replaces the PowerMockRule rule
@PrepareForTest({ CasSessionUtil.class })
public class TestClass extends AbstractShiroTest {

    @Autowired
    SomeService someService;

    @Before
    public void setUp() {
        Map<String, Object> newMap = new HashMap<String, Object>();
        newMap.put("userTimeZone", "Asia/Calcutta");
        Subject subjectUnderTest = mock(Subject.class);
        when(subjectUnderTest.getPrincipal())
            .thenReturn(LMPTestConstants.USER_NAME);
        Session session = mock(Session.class);
        when(session.getAttribute(LMPCoreConstants.USER_DETAILS_MAP))
            .thenReturn(newMap);
        when(subjectUnderTest.getSession(false))
            .thenReturn(session);
        setSubject(subjectUnderTest);
        // instead, add the getCarrierId() as a method that should be intercepted and return another value (i.e. the value you want)
        PowerMockito.stub(PowerMockito.method(CasSessionUtil.class, "getCarrierId"))
            .toReturn(1L);
    }

    @Test
    public void myTestMethod() {
        someService.doSomething();
    }
}