如何测试Spring Webmvc webservice休息

时间:2016-03-14 10:42:51

标签: java spring rest tomcat

我对Spring Webmvc有一点疑问。我正在尝试使用一个安静的Web服务创建一个Web应用程序,但我不知道它是否正常工作。

我有一个关于这个类的maven-webapp项目:

...
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
...

@RestController
@RequestMapping("/service")
public class PersoWsRest {

    @RequestMapping(value = "/lister", method = RequestMethod.GET)
    public List<Perso> listerPersos() {
        System.out.println("PASSAGE DS LE WEB SERVICE\n");

        List<Perso> res = new ArrayList<Perso>();

        res.add(new Perso("Test", "Un"));
        res.add(new Perso("Test", "Deux"));
        res.add(new Perso("Test", "Trois"));

        return res;
    }

}

并且,当我启动我的tomcat服务器(没有错误)时,我无法尝试使用我的Web服务。

我认为,这是两个问题:

  • 我没有使用正确的网址,但我正在尝试很多网址......所以......

  • 我没有正确配置Spring WebMvc。

你知道吗?感谢。

1 个答案:

答案 0 :(得分:0)

对于那些正在寻找样本代码的人来说,这是。

@RunWith(SpringJUnit4ClassRunner.class)
@WebMvcTest(PersoWsRest.class)
@AutoConfigureMockMvc
public class PersoWsRestTest{

 @Autowired
 MockMvc mockMvc;

 @Test
public void testListerPersos(){
    MvcResult mvcResult = this.mockMvc.perform(get("/service/lister")
            .andExpect(status().isOk())
            .andReturn();
//..... Further validation
      }    
    }