0

次のサービスがあります。

class MyMainService {

    def anotherService;

    def method1("data") {
         def response = anotherService.send("data")
    }

}

anotherService は、grails resources.groovy で定義された Bean です。

anotherService.send("data")をモックして、MyMainService の method1 を単体テストしたい

anotherService Bean とそのsend()メソッドの戻り値をモックし、 MyMainServiceSpecテスト クラスに挿入するにはどうすればよいですか?

私はgrails 2.3.8を使用しています。

ありがとう。

4

1 に答える 1

4

grails に組み込まれているデフォルトのモック フレームワークを使用するか、Spock フレームワークのモック スタイルを使用することを選択できます。私は Spock フレームワークを好みますが、選択はあなた次第です。以下は、ユニット スペックで使用できる grails の mockFor メソッドを使用してそれを行う方法の例です。

デフォルトの grails モックで MyMainService をテストします。

@TestFor(MyMainService)
class MyMainServiceSpec extends Specification {

    @Unroll("method1(String) where String = #pData")
    def "method1(String)"() {
        given: "a mocked anotherService"
        def expectedResponse = [:]  // put in whatever you expect the response object to be

        def mockAnotherService = mockFor(AnotherService)
        mockAnotherService.demand.send { String data ->
             assert data == pData
             return expectedResponse // not clear what a response object is - but you can return one. 
        }
        service.anotherService = mockAnotherService.createMock()  // assign your mocked Service 

        when:
        def response = service.method1(pData)

        then:
        response
        response == expectedResponse   

        where:
        pData << ["string one", "string two"]
    }
}
于 2014-09-23T02:50:02.587 に答える