I have a setup of a simple controller:
@Controller
@RequestMapping("/test")
public class TestController {
@RequestMapping(value = "/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody List<String> getTestString(){
List<String> sampleTest = new ArrayList<String>();
sampleTest.add("Test");
return sampleTest;
}
}
For this simple controller I'm trying to write a test in Spock using MockMVC:
class TestControllerTest extends Specification {
MockMvc mockMvc;
def setup(){
mockMvc = MockMvcBuilders.standaloneSetup(new TestController()).build();
}
def "testing TestController"(){
when:
MvcResult response = mockMvc.perform(get("/test/1"));
then:
response.andExpect(content().string('["Test"]'));
}
}
The JARs I have are:
Spring-test:4.0.5 Javax-servlet-api:3.0.1 spock-spring:0.7-groovy-2.0
The Error I get after running the test is this:
groovy.lang.MissingMethodException: No signature of method: com.crmservice.controller.TestControllerTest.get() is applicable for argument types: (java.lang.String) values: [/test]
Possible solutions: getAt(java.lang.String), grep(), grep(java.lang.Object), wait(), Spy(), any()
at com.crmservice.controller.TestControllerTest.testing TestController(TestControllerTest.groovy:27)
MockMVC class is part of Spring MVC test framework which helps in testing the controllers explicitly starting a Servlet container. In this MockMVC tutorial, we will use it along with Spring boot's WebMvcTest class to execute Junit testcases which tests REST controller methods written for Spring boot 2 hateoas example.
Right click on the project > Properties > Java Build Bath > Add External Jars and add spock-core-0.6-groovy-1.8. jar and check if Groovy Libraries are there in Build Path or not. If not click on Add Library and select Groovy Runtime Libraries and restart Eclipse. Now you should be able to run.
MockMvc provides support for Spring MVC testing. It encapsulates all web application beans and makes them available for testing. Let's see how to use it: private MockMvc mockMvc; @BeforeEach public void setup() throws Exception { this.mockMvc = MockMvcBuilders.webAppContextSetup(this.webApplicationContext).build(); }
Is the missing get
method imported?
You need the following line in imports block:
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With