在MockMvc中设置路径返回404?

时间:2017-09-06 17:57:14

标签: java spring unit-testing junit

我正在尝试使用MockMvc编写测试用例,并且它一直返回404(未找到页面)。我想这是因为我指的是错误的路线。如何正确指定路线?

我的考试班

success: function(data){
    console.log(data);
    const curSpan = document.getElementById(data);
    curSpan.innerHTML = data;
}

我的服务类

@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")));
   } 
}

SpringJUnitTestConfig.java

@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";
        }
    }
...

1 个答案:

答案 0 :(得分:0)

我认为您在控制器类上缺少@RestController注释。

请在此处查看示例:https://spring.io/guides/gs/rest-service/