2013-02-12 87 views
1

当使用MockFor时,我如何才能验证n方法是否被调用至少?我试着忽略设立后需求的方法调用,就像这样:使用MockFor,如何验证一个方法被调用至少n次?

import groovy.mock.interceptor.MockFor; 
import org.junit.Test 

class FilterTest { 

    interface Filter { 
     boolean isEnabled() 
    } 

    @Test 
    public void test() { 
     MockFor mockContext = new MockFor(Filter) 

     // Expect at least one call 
     mockContext.demand.isEnabled {true} 
     mockContext.ignore.isEnabled {false} 

     // Obtaining a usuable mock instance 
     def filter = mockContext.proxyInstance() 

     // Fake calling the method 
     filter.isEnabled() 
     filter.isEnabled() 

     // Verify invoked at least once?   
     mockContext.verify(filter) 
    } 
} 

不过,我得到一个断言失败:

junit.framework.AssertionFailedError: verify[0]: expected 1..1 call(s) to 
'isEnabled' but was called 0 time(s). 

回答

2

不能合并“需求”和“忽略“以这种方式,因为”忽略“声明压倒了”需求“声明。

相反,你可以指定的有效范围是这样的:

mockContext.demand.isEnabled(1..10) {true} 

将接受1至10号invokations的(但不是零或十或更多)。

我不知道有什么方法可以在范围中指定开放式结果的上限,但是,当您说“至少n次”时,暗示您需要这样做。

在大多数实际情况中,我相信你可以通过指定一个足够大的上界(比如100)来逃脱。

编辑:删除了“黑客”的建议(它没有像我期望的那样工作)

+0

谢谢,那正是我之后的! – Klarth 2013-02-14 10:58:20

相关问题