2017-07-21 2 views
0

1つのクラスですべてのMock構築メソッドをアセンブルしようとしています。 しかし、他のGroovyクラスでビルドメソッドで構築したMockオブジェクトを使用すると、 モックのスタブはうまくいくようですが、インタラクションチェックは機能しません。 ...どうすればいいですか?スーパークラスへのモック作成を移動MockTestingSpec.groovy他のクラスで構築されたMockでSpockのインタラクションが動作しない理由

class MockTestingSpec extends Specification{ 

    def "use mock from other class"(){ 
     setup:"construct mock builder" 
     def bldr = new MockBuilder() 

     when:"build mock by MockBuilder" 
     def mockObj = bldr.buildMock() 

     and:"build mock by private method of this class" 
     def builtAtThisClass = buildMock() 

     then:"check stubbing are working. these conditions were satisfied" 
     mockObj.getKey().equals("keyyyy") 
     mockObj.getValue() == 12345 
     builtAtThisClass.getKey().equals("keyyyy") 
     builtAtThisClass.getValue() == 12345 

     when:"put a mock to private method" 
     callMockGetter(builtAtThisClass) 

     then:"call each getter, these conditions were also satisfied" 
     1 * builtAtThisClass.getKey() 
     1 * builtAtThisClass.getValue() 

     when:"puta a mock that built by builder" 
     callMockGetter(mockObj) 

     then:"these conditions were NOT satisfied... why?" 
     1 * mockObj.getKey() 
     1 * mockObj.getValue() 
    } 
    // completely same method on MockBuilder. 
    private buildMock(String key = "keyyyy",Integer value = 12345){ 
     TestObject obj = Mock() 
     obj.getKey() >> key 
     obj.getValue() >> value 
     return obj 
    } 

    private callMockGetter(TestObject obj){ 
     obj.getKey() 
     obj.getValue() 
    } 
} 

MockBuilder.groovy

class MockBuilder extends Specification{ 

    public buildMock(String key = "keyyyy",Integer value = 12345){ 
     TestObject obj = Mock() 
     obj.getKey() >> key 
     obj.getValue() >> value 
     return obj 
    } 

    public static class TestObject{ 
     private String key 
     public String getKey(){ 
      return key 
     } 
     private Integer value 
     public Integer getValue(){ 
      return value 
     } 
    } 
} 
+1

あなたはとても 'MockTestingSpec'文句を言わない仕事から' MockBuilder'を使用して、他のスペックでモックを作成し、それらを再利用使用することはできません。 –

答えて

1

が代わりに動作します。このように、複数の仕様間で複雑なモック作成を再利用することができます。

abstract class MockCreatingSpec extends Specification { 
    createComplexMockInSuperClass() { 
     return Mock() 
    } 
} 
class MockTestingSpec extends MockCreatingSpec { 
    def "use mock from superclass"() { 
     given: 
     def mock = createComplexMockInSuperClass() 
     ... 
    } 
} 
関連する問題