[英]Setting path in MockMvc returns 404?
I am trying to write a test case using MockMvc and it keeps returning a 404 (Page not found). 我正在尝试使用MockMvc编写一个测试用例,并且它不断返回404(找不到页面)。 I think this is because I am specifying the route wrong. 我认为这是因为我指定的路线错误。 How do I specify the route correctly? 如何正确指定路线?
My test class 我的考试课
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {SpringJUnitTestConfig.class})
@WebAppConfiguration
public class HelloServiceTest {
@Autowired
private WebApplicationContext webApplicationContext;
HelloService hello;
private MockMvc mockMvc;
@Before
public void init(){
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext)
.build();
}
@Test
public void testUserInfoResponse() throws Exception{
mockMvc.perform(get("/helloservice/json/103"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(jsonPath("$", hasSize(1)))
.andExpect(jsonPath("$.login_name", is("jbray")));
}
}
My Service class 我的服务班
@Component
@Path("/helloservice")
public class HelloService{
//@TODO:Identify the current user
@Context
SecurityContext securityContext;
private static final String helloCache="hello";
private static Logger _logger;
public HelloService(){
_logger = Logger.getLogger(HelloService.class.getName());
}
@GET
@Path("/json/{p}")
@Produces({"application/json"})
public String getUserInfo(@PathParam("p") Integer userId){
try (Connection conn = conn()) {
String query = "SELECT * FROM pulse.customer WHERE userId = ?";
PreparedStatement preparedStmt = conn.prepareStatement(query);
preparedStmt.setInt(1, userId);
ResultSet rs=preparedStmt.executeQuery();
if(rs.next())
return "{login name: "+rs.getString("loginName")+"}";
return "{ login_name: 'shit broke yo'}";
}
catch(SQLException s){
return "sql exception:"+s.toString();
}
catch (NoResultException nre) {
//throw new UserNotFoundException(userId);
return "UserNotFoundException";
} catch (PersistenceException e) {
//throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
return "WebApplicationException";
}
}
...
SpringJUnitTestConfig.java SpringJUnitTestConfig.java
import com.sentiment360.pulse.services.HelloService;
import org.springframework.context.annotation.Bean;
public class SpringJUnitTestConfig {
@Bean
public HelloService getHelloService(){
return new HelloService();
}
}
I think you're missing a @RestController annotation on your controller class. 我认为您在控制器类上缺少@RestController批注。
See sample here: https://spring.io/guides/gs/rest-service/ 在此处查看示例: https : //spring.io/guides/gs/rest-service/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.