![](/img/trans.png)
[英]Junit MockMvc perform POST with path variable in URL return 404 not found
[英]Setting path in MockMvc returns 404?
我正在嘗試使用MockMvc編寫一個測試用例,並且它不斷返回404(找不到頁面)。 我認為這是因為我指定的路線錯誤。 如何正確指定路線?
我的考試課
@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")));
}
}
我的服務班
@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
import com.sentiment360.pulse.services.HelloService;
import org.springframework.context.annotation.Bean;
public class SpringJUnitTestConfig {
@Bean
public HelloService getHelloService(){
return new HelloService();
}
}
我認為您在控制器類上缺少@RestController批注。
在此處查看示例: https : //spring.io/guides/gs/rest-service/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.