Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MockMvc in Spock not working

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)
like image 763
tehras Avatar asked Dec 05 '14 03:12

tehras


People also ask

How does MockMvc perform work?

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.

How do I run Spock test in eclipse?

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.

What is MockMvc?

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(); }


1 Answers

Is the missing get method imported?

You need the following line in imports block:

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get
like image 89
Opal Avatar answered Oct 04 '22 03:10

Opal