eclipse调试器在Junit中不使用power规则

时间:2012-08-31 04:19:36

标签: eclipse junit powermock

我正在使用Mockito + PowerMock + PowerRule

开发Junits

请参阅我之前的问题:Getting javassist not found with PowerMock and PowerRule in Junit with Mockito

既然我已经成功运行了Junits,我遇到了一个奇怪的问题,即Eclipse调试器无法工作,即我的测试正在执行中,我不会停在断点上(使用SOP语句检查)

现在,当我从Junits中删除PowerRule时,调试器再次开始工作

我不知道为什么会这样。如果您对此有任何想法,请告诉我

由于

2 个答案:

答案 0 :(得分:2)

如果您在班级使用了注释@PrepareForTest({ClassName.class}),则会发生问题。 一种解决方法是在方法中声明该注释。即使在测试用例中使用了电源模拟,它也允许您调试它。

答案 1 :(得分:1)

在这种情况下不要使用 mockStatic,您将模拟整个静态类,这就是您将无法调试它的原因。

改为使用其中之一来避免模拟整个静态类:

  • spy

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

  • stub

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

  • 并使用 stub,如果方法有参数(例如字符串和布尔值),请执行以下操作:

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

这是finla代码,我选择使用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();
    }
}