测试spring boot rest api

时间:2016-07-24 17:17:57

标签: java spring rest testing spring-boot

我正在尝试在我的应用程序的rest api上编写测试。我正在使用春季靴子,运动衫休息。为了测试我试图使用MockMvc,但对于所有GET请求,我得到404状态代码。我尝试了不同的方法来运行它,但结果总是一样的。我想我错过了一些东西,所以请告诉你。

REST资源:

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

申请类:

@SpringBootApplication
@ComponentScan("com.glasierr.application")
@EnableJpaRepositories("com.glasierr.application.infrastructure.persistence.spring")
public class UserServiceApplication {
    public static void main(String[] args) {
        new SpringApplicationBuilder()
                .sources(UserServiceApplication.class)
                .run(args);
    }
}

泽西岛配置:

@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

1 个答案:

答案 0 :(得分:-1)

问题解决了。我在应用程序类中包含了配置,但它确实有用。

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