简体   繁体   中英

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). 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

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.

See sample here: https://spring.io/guides/gs/rest-service/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM