使用PowerMock-EasyMock时意外调用方法

时间:2014-06-23 08:29:39

标签: java mocking easymock powermock

我的问题似乎与嘲笑有些误解。测试代码。

public class CallHandler {
    private SqlSessionFactory sessionFactory;
    public CallHandler() {
        String resource = "mybatis/mybatis-config.xml";
        Reader reader;
        try {
            reader = Resources.getResourceAsReader(resource);
            sessionFactory = new SqlSessionFactoryBuilder().build(reader);
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }

    public String handleRequest(Call call) {
        // Some Implementation
    }
}

测试类

// I have excluded few unnecessary classes from @PrepareForTest for the post.

@RunWith(PowerMockRunner.class)
@PrepareForTest({SqlSessionFactoryBuilder.class, Resources.class, SqlSessionFactory.class, SqlSession.class})
public class TestCase0 extends TestCase{
    private SqlSessionFactory mockedSessionFactory = PowerMock.createMock(SqlSessionFactory.class);
    private SqlSession mockedSession = PowerMock.createMock(SqlSession.class);
    private CallMapper mockedMapper = PowerMock.createMock(CallMapper.class);
    private SqlSessionFactoryBuilder mockedSqlSessionFactoryBuilder= PowerMock.createMock(SqlSessionFactoryBuilder.class);
    // Others

    @Before
    public void setUp() {
    }

    @Test
    public void test0 () throws Exception {
        mockStatic(CallMapper.class);
        mockStatic(SqlSessionFactoryBuilder.class);
        mockStatic(Resources.class);
        expect(Resources.getResourceAsReader("mybatis/mybatis-config.xml")).andReturn(mockedReader);      expectNew(SqlSessionFactoryBuilder.class).andReturn(mockedSqlSessionFactoryBuilder);  expect(mockedSqlSessionFactoryBuilder.build(mockedReader)).andReturn(mockedSessionFactory);
        expect(mockedSessionFactory.openSession()).andReturn(mockedSession);
        // Few more expectations
        replayAll();
        assertThat(RESULT0).isEqualTo((new CallHandler()).handleRequest(call));
        verifyAll();
    }
}

这个对新SqlSessionFactoryBuilder的构建调用的模拟似乎没有生效,因为原来的build()被调用,因此错误。堆栈跟踪

java.lang.AssertionError: 
Unexpected method call Reader.close();
at org.easymock.internal.MockInvocationHandler.invoke(MockInvocationHandler.java:44)
at org.powermock.api.easymock.internal.invocationcontrol.EasyMockMethodInvocationControl.invoke(EasyMockMethodInvocationControl.java:91)
at org.powermock.core.MockGateway.doMethodCall(MockGateway.java:105)
at org.powermock.core.MockGateway.methodCall(MockGateway.java:168)
at org.apache.ibatis.session.SqlSessionFactoryBuilder.build(SqlSessionFactoryBuilder.java:58)
at org.apache.ibatis.session.SqlSessionFactoryBuilder.build(SqlSessionFactoryBuilder.java:38)
at com.kwench.integration.ivr.CallHandler.<init>(CallHandler.java:48)
at in.kwench.integration.ivr.TestCase0.test0(TestCase0.java:131)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.junit.internal.runners.TestMethod.invoke(TestMethod.java:68)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:310)
at org.junit.internal.runners.MethodRoadie$2.run(MethodRoadie.java:88)
at org.junit.internal.runners.MethodRoadie.runBeforesThenTestThenAfters(MethodRoadie.java:96)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.executeTest(PowerMockJUnit44RunnerDelegateImpl.java:294)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTestInSuper(PowerMockJUnit47RunnerDelegateImpl.java:127)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTest(PowerMockJUnit47RunnerDelegateImpl.java:82)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runBeforesThenTestThenAfters(PowerMockJUnit44RunnerDelegateImpl.java:282)
at org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie.java:86)
at org.junit.internal.runners.MethodRoadie.run(MethodRoadie.java:49)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.invokeTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:207)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.runMethods(PowerMockJUnit44RunnerDelegateImpl.java:146)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$1.run(PowerMockJUnit44RunnerDelegateImpl.java:120)
at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:33)
at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:45)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.run(PowerMockJUnit44RunnerDelegateImpl.java:118)
at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:104)
at org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:53)
at org.powermock.modules.junit4.PowerMockRunner.run(PowerMockRunner.java:53)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)

2 个答案:

答案 0 :(得分:4)

如果没有您正在测试的代码和测试类本身的完整示例,很难说您可能会出现问题。

话虽如此,我猜你的问题是你还没准备好使用静态方法的类。这些需要在测试类开始时在@PrepareForTest注释中提供。

PowerMock的文档提供了以下有关模拟静态方法的提示。我猜你错过了第2点。Here is the source for this documentation

  

模拟静态方法

     

快速摘要

     
      
  1. 在测试用例的类级别使用@RunWith(PowerMockRunner.class)注释。
  2.   
  3. 在测试用例的类级别使用@PrepareForTest(ClassThatContainsStaticMethod.class)注释。
  4.   
  5. 使用PowerMock.mockStatic(ClassThatContainsStaticMethod.class)来模拟此类的所有方法。
  6.   
  7. 使用PowerMock.replay(ClassThatContainsStaticMethod.class)将类更改为重播模式。
  8.   
  9. 使用PowerMock.verify(ClassThatContainsStaticMethod.class)将类更改为验证模式。
  10.   

您也在嘲笑SqlSessionFactoryBuilder的构造函数调用,因此您也需要考虑这方面的提示。 Here is the documentation for this

  

模拟新对象的构造

     

快速摘要

     
      
  1. 在测试用例的类级别使用@RunWith(PowerMockRunner.class)注释。
  2.   
  3. 在测试用例的类级别使用@PrepareForTest(ClassThatCreatesTheNewInstance.class)注释。
  4.   
  5. 使用PowerMock.createMock(NewInstanceClass.class)创建应该构造的类的模拟对象(让我们将其称为mockObject)。
  6.   
  7. 使用PowerMock.expectNew(NewInstanceClass.class).andReturn(mockObject)来期望NewInstanceClass.class类型的对象的新构造,而是返回模拟对象。
  8.   
  9. 使用PowerMock.replay(mockObject,NewInstanceClass.class)将模拟对象和类更改为重放模式,或者使用PowerMock.replayAll()方法。
  10.   
  11. 使用PowerMock.verify(mockObject,NewInstanceClass.class)将模拟对象和类更改为验证模式,或者使用PowerMock.verifyAll()方法。
  12.   

考虑到这些提示,我为您提供的尝试测试的方法生成了以下测试方法。这个测试顺利通过。

@RunWith(PowerMockRunner.class)
@PrepareForTest({CallHandler.class, SqlSessionFactoryBuilder.class, Resources.class})
public class CallHandlerTest {

    private static final String RESULT0 = "";

    @Test
    public void test0 () throws Exception {
        final Reader mockedReader = EasyMock.createMock(Reader.class);
        final SqlSessionFactoryBuilder mockedSqlSessionFactoryBuilder = EasyMock.createMock(SqlSessionFactoryBuilder.class);
        final SqlSessionFactory mockedSessionFactory = EasyMock.createMock(SqlSessionFactory.class);

        PowerMock.mockStatic(SqlSessionFactoryBuilder.class);
        PowerMock.mockStatic(Resources.class);

        PowerMock.expectNew(SqlSessionFactoryBuilder.class).andReturn(mockedSqlSessionFactoryBuilder);
        EasyMock.expect(Resources.getResourceAsReader("mybatis/mybatis-config.xml")).andReturn(mockedReader);
        EasyMock.expect(mockedSqlSessionFactoryBuilder.build(mockedReader)).andReturn(mockedSessionFactory);

        PowerMock.replayAll();
        assertThat(RESULT0).isEqualTo((new CallHandler()).handleRequest(new Call()));
        PowerMock.verifyAll();
    }
}

答案 1 :(得分:1)

代码覆盖率与powermock.mockStatic之间存在冲突。

代码覆盖工具$ jacocoInit静态方法进入所有类来收集代码覆盖率。运行测试用例时,mockStatic模拟$ jacocoInit静态方法,该方法导致预期的静态方法调用。

您可以通过在静态方法上创建部分模拟来绕过问题,例如PowerMock.mockStaticPartial(TheClass.class,&#34; theStaticMethod&#34;),以便power mock不会触及$ jacocoInit方法。