java - 方法调用计数断言

标签 java unit-testing easymock powermock

我刚刚开始使用 PowerMock 和 EasyMock,我对模拟方法调用的计数方式有些困惑。

示例代码:

class ClassToBeTested{
 private boolean toBeMocked(Integer i){
  return i%2==1; 
  }
 }

和测试代码:

@RunWith(PowerMockRunner.class)
@PrepareForTest(ClassToBeTested.class)
public class ClassToBeTestedTest{

 private final Integer i=2;
 ClassToBeTested underTest;

 @Before
 public void setUp() throws Exception {
  underTest=PowerMock.createPartialMock(ClassToBeTested.class,
                    "toBeMocked");
  PowerMock.expectPrivate(underTest, "toBeMocked", i)
            .andReturn(true);
  PowerMock.replay(underTest);
 }
 @Test
 public dummyTest(){
  Assert.assertTrue(underTest.toBeMocked(i);
  //the call is: underTest.toBeMocked(2)
  //so the computation is return 2%2==1; google says it 0 :)
  //thus real method would return 0==1 (false)
  //mocked one will return true, assertion should pass, that's ok
  //RERUN ASSERTION
  Assert.assertTrue(underTest.toBeMocked(i);
  //method invocation count should be now 2
}

  @After
  public void tearDown() {
   PowerMock.verify(underTest);
   //WILL FAIL with exception saying
   //the mocked method has not been called at all
   //expected value (obvious) is one
}

我的问题是,为什么模拟方法调用预期会失败? 为什么验证 ClassUnderTest 会显示根本没有调用模拟方法?

最佳答案

它对我有用,在将期望行更改为:

 PowerMock.expectPrivate(underTest, "toBeMocked", i).andReturn(true).times(2);

即使没有那个变化,也不能说被 mock 的母亲没有被召唤。它说

  Unexpected method call toBeMocked(2):
    toBeMocked(2): expected: 1, actual: 2

您使用的是最新的 PowerMock 和 EasyMock 版本吗?

关于java - 方法调用计数断言,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10006240/

相关文章:

java - 如何在java中创建类似于(key, value)属性文件的(key, value1, value2)文件

php - 在 AppController 中对 beforeFilter() 和 beforeRender() 进行单元测试的正确方法

Python,单元测试 : Can one make the TestRunner completely quiet?

python - PyCharm:创建测试 --> 目标目录?

java - 知道如何为下面的代码编写 UT 吗?

java - 使用 EasyMock 模拟具体类

java - Android:函数在 Thread 中不起作用,但在其他情况下起作用(尝试添加 ProgressDialog)

java - 遵守平等约束

java - 使用 Cobertura 从代码覆盖范围中排除方法

java - 在同一对象中测试方法时如何模拟对象中的方法