You can create an attribute in your test to control that:
class MyTest {
int someMethodCount
@Before
void setup() {
fooMock.demand.someMethod(3..3) { ->
someMethodCount++
...
}
}
}
質問
I want to mock a object method that is called many times, and each times the result must be different.
Here what I'm trying to do:
fooMock.demand.someMethod(3..3) { ->
//call1
if (**some condition**)
return 1
//call2
if (**some condition**)
return 2
//call3
if (**some condition**)
return 3
}
So, is there a way to know what is the current call number ? or do you offers something better ?
It will be possible to do that in Grails 2.3-M2 (http://jira.grails.org/browse/GRAILS-4611) but until then, did someone has a workaround ?
解決
You can create an attribute in your test to control that:
class MyTest {
int someMethodCount
@Before
void setup() {
fooMock.demand.someMethod(3..3) { ->
someMethodCount++
...
}
}
}
他のヒント
If you do not care about strict mocking and are only unit testing someMethod
then you can use the primitive methodology of using maps:
void testSomething() {
def mockUtil = ["someMethod" : {param->
//I have used param only to handle conditional logics
//param can be optional
if(param == 1)return "John"
if(param == 2)return "Nancy"
if(param == 3)return "Mark"
}]
assert mockUtil.someMethod(1) == "John"
assert mockUtil.someMethod(2) == "Nancy"
assert mockUtil.someMethod(3) == "Mark"
}