0

私は一緒に働いています

  • STS
  • グラドル
  • スポック・コア
  • スポックレポート
  • スポックスプリング
  • Spring MVC テスト

次のテストコードがあります。

@WebAppConfiguration
@ContextConfiguration(classes=[RootApplicationContextConfig.class,ServletApplicationContextConfig.class])
@SuppressWarnings("deprecation")
class PersonaXmlFindOneControllerTest extends Specification {

    @Autowired
    private WebApplicationContext webApplicationContext;

    private MockMvc mockMvc;

    private PersonaXmlFindOneController personaXmlFindOneController 

    def setup(){
        mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();

        personaXmlFindOneController = webApplicationContext.getBean(PersonaXmlFindOneController.class);

        println personaXmlFindOneController.toString()

    }

    def "findOneRequestParamById deberia ser llamado"(){

        String url = null
        ResultActions resultActions = null

        given: "The URL being used "

           url = "some url to test"

        when: "When the URL is being calling with a GET"

            resultActions = mockMvc.perform(get(url, PersonaControllerSupport.ID)).andDo(print())

        then: "...."

            resultActions.andExpect(status().isOk())
                         .andExpect(content().contentType(MediaType.APPLICATION_XML))
                         .andExpect(xpath("persona").exists())
                         .andExpect(xpath("persona").nodeCount(1))
….

        //then: 

            //1 * personaXmlFindOneController.findOneRequestParamById(_ as String)           

    }

コードは正常に動作します。合格です。

さらに : andDo (print())のおかげで Gradle テスト レポートを介して、 personaXmlFindOneController.findOneRequestParamById が呼び出されたことを確認できます。

その意味は

Handler:

Type = com.manuel.jordan.controller.xml.PersonaXmlFindOneController
Method = public com.manuel.jordan.domain.xml.PersonaXml com.manuel.jordan.controller.xml.PersonaXmlFindOneController.findOneRequestParamById(java.lang.String)

Now If enable

//then: 
    //1 * personaXmlFindOneController.findOneRequestParamById(_ as String)           

コードが失敗し、

Too few invocations for:

1 * personaXmlFindOneController.findOneRequestParamById(_ as String)   (0 invocations)

Unmatched invocations (ordered by similarity):

None

setup メソッドで取得されていることを確認します。

personaXmlFindOneController = webApplicationContext.getBean(PersonaXmlFindOneController.class); 

したがって、何が欠けていて、何が間違っているのでしょうか?

4

1 に答える 1

2

2 つの異なるモック メカニズムを混在させています。

Spring のもの (MockMVC) と Spock のものがあります。

Spock は、それ自体で作成されたモック (つまり、Spock Mock() メソッドで作成されたもの) のみを検証できます。コード内で Spock モックを作成しないため、Spock モックは機能しません。

Spock のみでモックを作成する方法を理解するための完全なモッキング ガイドについては、Spock の公式ドキュメントを参照してください。

あなたの特定の例では、元のコードは正しいので、そのままにしておく必要があります。Spock モッキング メカニズムを常に使用する必要はありません。Spring テスト機能のみを使用する Spock テストを使用することはまったく問題ありません。

于 2015-11-25T10:13:23.853 に答える