模拟静态方法不起作用

时间:2017-03-29 12:53:29

标签: unit-testing mocking mockito powermock easymock

我编写的代码只是使用powermock模拟静态方法。

在运行测试用例时,会抛出没有模拟可用的最后一次调用

在调试时,发现它在expect语句中被抛出。

异常throwm的堆栈跟踪:

java.lang.IllegalStateException: no last call on a mock available
at org.easymock.EasyMock.getControlForLastCall(EasyMock.java:466)
at org.easymock.EasyMock.expect(EasyMock.java:444)
at junit.util.mock.Test.test1(Test.java:26)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
....
....

写的测试类:

import static org.junit.Assert.assertEquals;

import static org.powermock.api.easymock.PowerMock.mockStatic;
import static  org.powermock.api.support.membermodification.MemberMatcher.constructor;

import org.easymock.EasyMock;
import static org.powermock.api.support.membermodification.MemberModifier.suppress;
import static org.easymock.EasyMock.expect;
import org.junit.runner.RunWith;
import org.powermock.api.easymock.PowerMock;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import static org.powermock.api.easymock.PowerMock.replayAll;

import Testing;

@RunWith(PowerMockRunner.class)
@PrepareForTest({Testing.class})
public class Test {

 @org.junit.Test
 public void test1() {
mockStatic(Testing.class);
expect(Testing.getWord()).andReturn("my Cal").anyTimes();
PowerMock.replay(Testing.class);
PowerMock.verify(Testing.class);
assertEquals(Testing.getWord(),"my Cal");
}
}

待测班级:

public class Testing {
public static String getWord() {
    return "from test";
    }
}

1 个答案:

答案 0 :(得分:0)

我试过你的代码,它运作得很好。所以我不知道该说些什么。有一点不正确的是verify应该在最后。但这不是造成这个问题的原因。

我可以提供我使用的依赖项,以防它与之相关。

<dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <version>4.12</version>
  <scope>test</scope>
</dependency>
<dependency>
  <groupId>org.easymock</groupId>
  <artifactId>easymock</artifactId>
  <version>3.4</version>
</dependency>
<dependency>
  <groupId>org.powermock</groupId>
  <artifactId>powermock-core</artifactId>
  <version>1.6.6</version>
</dependency>
<dependency>
  <groupId>org.powermock</groupId>
  <artifactId>powermock-api-easymock</artifactId>
  <version>1.6.6</version>
</dependency>
<dependency>
  <groupId>org.powermock</groupId>
  <artifactId>powermock-module-junit4</artifactId>
  <version>1.6.6</version>
</dependency>