因此,我不认为有很多从春天进行测试控制器用SpringMVC在这里Mockmvc的问题,但我通过弹簧教程阅读 https://spring.io/guides/tutorials/rest/2/ 那里有很多有,但我只是试图用一个id参数在web服务上做一个简单的GET。控制器是这样的:为Spring RESTful Web服务建立MockMVC
@RestController
@RequestMapping("/demandrest")
public class DemandServicesController {
@Autowired
DemandService demandService;
@RequestMapping(value = "/demand/{$id}", method = RequestMethod.GET, headers= "Accept-application/jsson")
public Demand readDemand(@RequestParam(value="id", required=true) String id){
return demandService.readDemand(new Long(id));
}
,我写了使用org.springframework.test.web.servlet.MockMvc一个单元测试,我试图模拟出(真的存根)的服务电话和做一个断言在状态代码和我得到状态码404我的测试看起来像这样
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.standaloneSetup;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.test.web.servlet.MockMvc;
public class DemandServicesControllerTest {
MockMvc mockMvc;
@InjectMocks
DemandServicesController demandServicesController = new DemandServicesController();
@Mock
DemandService demandService;
@Before
public void setUpUnitTest() throws Exception {
MockitoAnnotations.initMocks(this);
this.mockMvc = standaloneSetup(demandServicesController).
setMessageConverters(new MappingJackson2HttpMessageConverter()).build();
}
@After
public void tearDown() throws Exception {
}
@Test
public void testReadDemandState() throws Exception {
Long id = new Long(99);
Demand demand = new Demand();
demand.setDescription("description");
when(demandService.readDemand(id)).thenReturn(demand);
this.mockMvc.perform(get("/demandrest/demand/{id}",id.toString()).
accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk());
}
}
我一些其他的事情,我打中立柱之前我会提到。所以看看这个教程中的例子,我试图挑选那些我只会用到的东西,所以它不是一个确切的副本。我必须做的一个很大的区别,我怀疑这与测试插件的配置有什么关系,我不得不实例化控制器,其中示例足够聪明以知道创建实例。此外,该示例依靠Gradle进行项目设置,并且我只有这个项目的一个pom文件。不知道这是否有所作为。看起来像这是新东西,但这是一个非常简单的例子。预先感谢您的帮助。