Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 测试spring boot rest api时未找到404_Java_Spring_Rest_Testing_Spring Boot - Fatal编程技术网

Java 测试spring boot rest api时未找到404

Java 测试spring boot rest api时未找到404,java,spring,rest,testing,spring-boot,Java,Spring,Rest,Testing,Spring Boot,我正在尝试在我的应用程序的RESTAPI上编写测试。我用的是弹簧靴,球衣休息。对于测试,我尝试使用MockMvc,但是对于所有GET请求,我都会得到404状态代码。我尝试了不同的方法来运行它,但结果总是一样的。我想我遗漏了什么,所以,请给我建议 休息资源: @Component @Path("/v1/users") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @Transactional(

我正在尝试在我的应用程序的RESTAPI上编写测试。我用的是弹簧靴,球衣休息。对于测试,我尝试使用MockMvc,但是对于所有GET请求,我都会得到404状态代码。我尝试了不同的方法来运行它,但结果总是一样的。我想我遗漏了什么,所以,请给我建议

休息资源:

@Component
@Path("/v1/users")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@Transactional(readOnly = true)
public class UserResource {
    private final UserService userService;

    @Inject
    public UserResource(UserService userService) {
        this.userService = userService;
    }

    @GET
    public Collection<User> list() {
        return userService.fetchAllUsers();
    }
}
泽西配置:

@Configuration
@ApplicationPath("/api")
public class JerseyConfig extends ResourceConfig {
    public JerseyConfig() {
        packages("com.glasierr.application.resource");
    }
}
测试属性代码段:

server:
  port: 9999

database:
  driverName: org.h2.Driver
  url: jdbc:h2:mem:test;IGNORECASE=TRUE;DB_CLOSE_ON_EXIT=FALSE;DB_CLOSE_DELAY=-1
  username: sa
  password:
  hibernateDialect: org.hibernate.dialect.H2Dialect
  hibernateShowSql: true
  hibernateHbm2ddl: update
测试等级:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(UserServiceApplication.class)
@WebIntegrationTest
public class UserResourceTest {

    @InjectMocks
    private UserResource userResource;

    @Mock
    private UserService userService;

    @Autowired
    private WebApplicationContext context;

    private MockMvc mvc;

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);

        mvc = MockMvcBuilders
                .webAppContextSetup(context)
                .build();
    }

    @Test
    public void test() throws Exception {
        when(userService.fetchAllUsers()).thenReturn(Arrays.asList(new User("user1"), new User("user2")));

        mvc.perform(get("/api/v1/users").accept(MediaType.parseMediaType("application/json;charset=UTF-8")))
                .andExpect(status().isOk());
    }
}
一些控制台输出:

2016-07-24 20:17:40.909  INFO 5532 --- [           main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2016-07-24 20:17:42.121  INFO 5532 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@11c9af63: startup date [Sun Jul 24 20:17:32 EEST 2016]; root of context hierarchy
2016-07-24 20:17:42.264  INFO 5532 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2016-07-24 20:17:42.266  INFO 5532 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2016-07-24 20:17:42.320  INFO 5532 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2016-07-24 20:17:42.320  INFO 5532 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2016-07-24 20:17:42.413  INFO 5532 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2016-07-24 20:17:42.877  INFO 5532 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 9999 (http)
2016-07-24 20:17:42.885  INFO 5532 --- [           main] e.s.h.a.resource.OperatorResourceTest    : Started OperatorResourceTest in 10.898 seconds (JVM running for 13.017)
2016-07-24 20:17:43.126  INFO 5532 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring FrameworkServlet ''
2016-07-24 20:17:43.127  INFO 5532 --- [           main] o.s.t.web.servlet.TestDispatcherServlet  : FrameworkServlet '': initialization started
2016-07-24 20:17:43.148  INFO 5532 --- [           main] o.s.t.web.servlet.TestDispatcherServlet  : FrameworkServlet '': initialization completed in 21 ms

java.lang.AssertionError: Status 
Expected :200
Actual   :404

问题解决了。我已经在应用程序类中包含了配置,它很有效

@SpringBootApplication
@Configuration  
@Import({JerseyConfig.class})
public class UserServiceApplication {
    public static void main(String[] args) {
        new SpringApplicationBuilder()
                .sources(UserServiceApplication.class)
                .run(args);
    }    
}

尝试在测试类中加载JerseyConfig。您只加载UserServiceApplication@SpringApplicationConfigurationUserServiceApplication.class,JerseyConfig会添加api路径
@SpringBootApplication
@Configuration  
@Import({JerseyConfig.class})
public class UserServiceApplication {
    public static void main(String[] args) {
        new SpringApplicationBuilder()
                .sources(UserServiceApplication.class)
                .run(args);
    }    
}