【问题标题】:eclipse debugger not working with power Rule in Juniteclipse 调试器无法在 Junit 中使用 power Rule
【发布时间】:2012-08-25 21:18:37
【问题描述】:

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

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

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

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

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

谢谢

【问题讨论】:

  • IntelliJ IDEA 中的同样问题。
  • Eclipse 中同样的问题

标签: eclipse junit powermock


【解决方案1】:

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

【讨论】:

  • 我试过 @PrepareForTest({ElasticSearchUtility.class}) @Test public void getIndexesTobedeleted() throws Exception {..} 但还是同样的问题
  • 你的意思是源代码方法/依赖方法?
  • 上述解决方案有效,一旦将@PrepareForTest 移至方法级别就可以进行调试。谢谢。使用eclipse IDE 2019-03
【解决方案2】:

在这种情况下不要使用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();
    }
}

【讨论】:

    猜你喜欢
    • 2011-03-10
    • 2020-10-06
    • 2020-10-20
    • 2015-05-08
    • 1970-01-01
    • 2010-09-30
    • 1970-01-01
    • 2018-12-26
    • 2014-04-16
    相关资源
    最近更新 更多