10

我正在使用 Mockito + PowerMock + PowerRule 开发 Junits

参考我的上一个问题:Getting javassist not found with PowerMock and PowerRule in Junit with Mockito

现在我的 Junits 已经成功运行,我遇到了一个奇怪的问题,即 Eclipse 调试器无法正常工作,即我没有在断点处停止,尽管我的测试正在执行(使用 SOP 语句检查)

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

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

谢谢

4

2 回答 2

4

如果您在类级别使用了注释@PrepareForTest({ClassName.class}),那么就会出现问题。一种解决方法是在方法中声明该注释。即使在测试用例中使用了电源模拟,它也允许您对其进行调试。

于 2015-06-23T08:29:10.263 回答
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();
    }
}
于 2021-06-11T05:30:11.827 回答