use*_*451 8 testing grails groovy constructor mocking
我正在测试一些使用java库的groovy代码,我想模拟库调用,因为他们使用网络.所以测试中的代码看起来像:
def verifyInformation(String information) {
def request = new OusideLibraryRequest().compose(information)
new OutsideLibraryClient().verify(request)
}
Run Code Online (Sandbox Code Playgroud)
我尝试使用MockFor和StubFor,但我收到的错误如下:
No signature of method: com.myproject.OutsideLibraryTests.MockFor() is applicable for argument types: (java.lang.Class) values: [class com.otherCompany.OusideLibraryRequest]
Run Code Online (Sandbox Code Playgroud)
我正在使用Grails 2.0.3.
cha*_*wit 10
我刚刚发现我们总是可以通过MetaClass覆盖构造函数,因为Grails 2将在每次测试结束时重置MetaClass修改.
这个技巧比Groovy更好MockFor.例如,AFAIK,Groovy MockFor不允许我们模拟JDK的类java.io.File.但是在下面的例子中,你不能使用File file = new File("aaa")真正的对象类型是a Map,而不是a File.这个例子是Spock规范.
def "test mock"() {
setup:
def fileControl = mockFor(File)
File.metaClass.constructor = { String name -> [name: name] }
def file = new File("aaaa")
expect:
file.name == "aaaa"
}
Run Code Online (Sandbox Code Playgroud)
MockFor构造函数的第二个可选参数是interceptConstruction.如果将此属性设置为true,则可以模拟构造函数.例:
import groovy.mock.interceptor.MockFor
class SomeClass {
def prop
SomeClass() {
prop = "real"
}
}
def mock = new MockFor(SomeClass, true)
mock.demand.with {
SomeClass() { new Expando([prop: "fake"]) }
}
mock.use {
def mockedSomeClass = new SomeClass()
assert mockedSomeClass.prop == "fake"
}
Run Code Online (Sandbox Code Playgroud)
但是请注意,你只能模仿像这样的groovy对象.如果您坚持使用Java库,则可以将Java对象的构造转换为工厂方法并对其进行模拟.
| 归档时间: |
|
| 查看次数: |
6101 次 |
| 最近记录: |