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)

现在如果启用

//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

您正在混合两种不同的模拟机制。

有 Spring 一种(MockMVC)和 Spock 一种。

Spock 只能验证自己创建的模拟(即使用 Spock Mock() 方法创建的模拟)。您没有在代码中创建任何 Spock 模拟,因此 Spock 模拟将不起作用。

有关完整的模拟指南,请参阅 Spock 的官方文档,以了解如何仅使用 Spock 创建模拟。

在您的特定示例中,您的原始代码是正确的,应该保持这种状态。您不必总是使用 Spock 模拟机制。拥有一个只使用 Spring 测试工具的 Spock 测试是非常好的。

于 2015-11-25T10:13:23.853 回答