在Groovy中嘲讽待测单元的单一方法 [英] Mock a single method of unit under test in Groovy
问题描述
我有一个简单的类,比如
class SomeClass {
def foo(){
def bar = bar()
switch(bar){
返回格式为
}
}
def bar(){
返回someValue
}
}
我已经编写了完整的单元测试 bar()
。现在我需要为 foo()
编写单元测试,这非常依赖于使用 bar()
方法。我不想像 bar()
那样重复设置阶段,所以我想通过简单地返回我想要的值来模拟它。
我知道Groovy通过像 SomeClass.property =Hello World
那样简单地定义它来支持这种嘲讽 。另外,这可以通过
我尝试了 MockFor
,如
def uut = new MockFor(SomeClass)
uut.demand.bar {/ * some values * /}
uut.use {
assert uut .foo()== expected
}
但它给了我$
groovy.lang.MissingMethodException:方法没有签名:groovy.mock.interceptor.MockFor.foo()适用于参数类型:()values :[]
更新
事实上,我想出了一个使用子分类的简单解决方案。在测试方法中,我创建了一个 SomeClass
的子类,其中我重写了我希望模拟/存根的方法。之后,使用一个子类的实例给了我需要的东西。
虽然这看起来有些粗糙。如果你想模拟由 bar()返回的值
SomeClass
的单个实例,您可以使用元编程。在Groovy控制台中尝试以下操作: class SomeClass {
def foo(){
}
def bar(){
return'real value'
}
}
def uut = new SomeClass()
uut.metaClass.bar = {
返回'模拟值'
}
断言'模拟值'== uut.bar()
如果您想要模拟 bar()
code> SomeClass ,替换为:
uut.metaClass.bar = {
返回'模拟值'
}
与:
SomeClass.metaClass.bar = {
返回'模拟值'
}
I have a simple class like
class SomeClass {
def foo() {
def bar= bar()
switch( bar ) {
return something based on format
}
}
def bar() {
return someValue
}
}
I've already written complete unit tests for the bar()
. Now I need to write unit tests for foo()
which is heavily dependant on the use of bar()
method. I don't want to duplicate the setup phase as done for bar()
, so I'd like to mock it by simply returning values I want.
I'm aware that Groovy supports this sort of "mocking" easily by simply defining it like SomeClass.property = "Hello World"
. Also, this can be done with collaborators as SomeClass.service = myMockedService
. But I've not found a way to accomplish this with methods inside the unit under tests. Is there?
I tried with MockFor
as in
def uut = new MockFor( SomeClass )
uut.demand.bar{ /* some values */ }
uut.use {
assert uut.foo() == expected
}
but it gives me
groovy.lang.MissingMethodException: No signature of method: groovy.mock.interceptor.MockFor.foo() is applicable for argument types: () values: []
UPDATE
In fact, I came up with a simple solution of using sub-classing. In the test method I create a subclass of SomeClass
where I override the method I wish to mock/stub. After this, using an instance of the subclass gives me what I need.
This seems a bit rough, though. Any other suggestions on this?
If you want to mock the value returned by bar()
for a single instance of SomeClass
you can use metaprogramming. Try the following in the Groovy console:
class SomeClass {
def foo() {
}
def bar() {
return 'real value'
}
}
def uut = new SomeClass()
uut.metaClass.bar = {
return 'mock value'
}
assert 'mock value' == uut.bar()
If you want to mock bar()
for all instances of SomeClass
, replace this:
uut.metaClass.bar = {
return 'mock value'
}
with:
SomeClass.metaClass.bar = {
return 'mock value'
}
这篇关于在Groovy中嘲讽待测单元的单一方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!