【问题标题】:Method invocation count Assertion方法调用计数断言
【发布时间】:2012-04-04 06:52:52
【问题描述】:

我刚开始使用 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 会发现根本没有调用 mocked 方法?

【问题讨论】:

    标签: java unit-testing easymock powermock


    【解决方案1】:

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

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

    即使没有这种变化,也不能说被嘲笑的母亲没有被召唤。它说

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

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

    【讨论】:

    • 我的错 我上面介绍的示例是根据实际问题提出的,但不幸的是,我错过了一个解释我的问题的重要问题:
    • 我的错 我上面介绍的示例是根据实际问题提出的,但不幸的是,我错过了一个解释我的问题的重要问题:我在实际示例中的 Test dummyMethod 分为两个运行相同模拟方法的 Test 方法。我的期望是,所有 Test 方法都只会运行模拟方法一次。我认为 错误地 比 After 方法将在所有 Test 方法执行后被调用 一次。一种测试方法根本不调用模拟方法,所以实际调用是 O,预期为 1,因此我的问题......
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-24
    • 2019-11-15
    • 2016-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多