Spock Spring 启动测试

Spock Spring boot testing

我正处于 spock 和 groovy 的初始阶段,我正在尝试测试一个简单的 spring 引导应用程序并获得

下面是我的 java 和 groovy 代码以及异常详细信息

Condition not satisfied:

mvc.perform(get('/hello')).andExpect(status().isOk())
|           |
|           groovy.lang.MissingMethodException: No signature of method: org.spockframework.controllers.TestControllerSpec.get() is applicable for argument types: (java.lang.String) values: [/hello]
|           Possible solutions: getAt(java.lang.String), grep(), grep(java.lang.Object), wait(), Spy(), getMvc()
org.springframework.test.web.servlet.MockMvc@6bb68f5

at org.spockframework.controllers.TestControllerSpec.spring context loads for web mvc slice(TestControllerSpec.groovy:28)
Caused by: groovy.lang.MissingMethodException: No signature of method: org.spockframework.controllers.TestControllerSpec.get() is applicable for argument types: (java.lang.String) values: [/hello]
Possible solutions: getAt(java.lang.String), grep(), grep(java.lang.Object), wait(), Spy(), getMvc()

and above exception comes when some argument is missing don't what argument and how to pass argument below is my code

TestController.java

@RequestMapping(value = "/hello")
@ResponseBody
public String sayHelloWorld() {
    return "hello world";
}

TestControllerSpec.groovy

import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status

import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest
import org.springframework.boot.test.context.TestConfiguration
import org.springframework.context.annotation.Bean
import org.springframework.test.context.ContextConfiguration
import org.springframework.test.web.servlet.MockMvc
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders

import spock.lang.Specification
import spock.lang.Unroll
import spock.mock.DetachedMockFactory

@ContextConfiguration
@WebMvcTest(TestController)
class TestControllerSpec extends Specification {

 @Autowired
 MockMvc mvc;

 @Unroll
 def "spring context loads for web mvc slice"() {

    expect: "controller is available"
    mvc.perform(get('/hello')).andExpect(status().isOk())
 }

 @TestConfiguration
 static class MockConfig {
    def detachedMockFactory = new DetachedMockFactory();
 }
}

我确定我的代码遗漏了什么

您没有导入方法 get。尝试添加它

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get

Groovy 是动态语言,因此即使您忘记了导入,它也能让您 运行 您的代码,因为您可能会在 运行 时间内将方法附加到 class。当您使用 Groovy 进行写作时(也包括任何其他语言,但尤其是 Groovy),请始终注意 IDE 中的警告。