0

Grails 3.2.8Spockフレームワークをテストに使用し、次のコントローラー クラスを指定します。

class SomeController {
    def doSomething() {
        // do a few things, then:
        someOtherMethod()
    }

    protected void someOtherMethod() {
        // do something here, but I don't care
    }
}

doSomething()メソッドをテストして、someOtherMethod()正確に 1 回呼び出されることを確認するにはどうすればよいですか?

これは失敗した私の試みです:

@TestFor(SomeController)
class SomeControllerSpec extends Specification {
    void "Test that someOtherMethod() is called once inside doSomething()"() {
        when:
        controller.doSomething()

        then:
        1 * controller.someOtherMethod(_)
    } 
}

エラーメッセージ:

Too few invocations for:

1 * controller.someOtherMethod(_)   (0 invocations)

注: 当面の問題に焦点を当てるために、インポートは省略されています

4

1 に答える 1

0

コントローラーはモックされたオブジェクトではないため、これを行うことはできません。代わりに、次のようなメタクラスを使用する必要があります。

@TestFor(SomeController)
class SomeControllerSpec extends Specification {
    void "Test that someOtherMethod() is called once inside doSomething()"() {
        given:
            Integer callsToSomeOtherMethod = 0
            controller.metaClass.someOtherMethod = {
                callsToSomeOtherMethod++
            }
        when:
            controller.doSomething()

        then:
            callsToSomeOtherMethod == 1
    } 
}
于 2017-05-04T09:49:24.370 に答える