在Spring Boot中测试Rest API时,Spring Test返回404而不是200

时间:2017-05-01 15:30:34

标签: java spring spring-mvc spring-boot spring-test

简而言之,我的控制器是这样的:

@RestController
@RequestMapping(value = "/assetservice/rest/v1.0/")
public class LibrarySearchController {


    private LibraryService libServices;
    @Autowired
    public LibrarySearchController(LibraryService libraryService)
    {
        this.libServices = libraryService;
    }

    /**
     * Get Libraries for given Collection ids 
     * @param collectionIds
     * @return List<MediaLibraryDetail>
     */

    @RequestMapping("libraries/search/")

    public MediaLibraries getLibraryTree(@RequestParam(value="collectionIds", defaultValue="")String[] collectionIds, @RequestParam(value="offset",required=false,defaultValue = "0") int offset, @RequestParam(value="limit",required=false
            ,defaultValue = "10") int limit) throws Exception{


        MediaLibraries mediaLibraries = libServices.getAllLibraries(collectionIds, offset, limit);
        System.out.println(mediaLibraries);
        if(mediaLibraries.getLibraryElements()== null)
            throw new InvalidCollectionIdFoundException();

        return mediaLibraries;

    }
}

基本上它正在做的是接受一些输入,比如collectionId(一些数字的数组),一些偏移和一些限制,并试图回馈一些数据。

为了测试这个控制器,我使用spring测试框架编写了一个测试。我已经简化了在这里提问的测试。

@RunWith(SpringRunner.class)
@WebMvcTest(value = LibrarySearchController.class, secure = false)
public class LibrarySearchControllerMockMvcTest {

//Some other code  was here
@Test
    public void testVerifyRetrievedMediaLibrariesJson() throws Exception{


        MediaLibraries mediaLibraries = createMediaLibrariesObject();//creates mediaLibraries Object; code not shown
        given(libraryService.getAllLibraries(collectionId,offset,limit)).willReturn(mediaLibraries); //mocking the service

        mvc.perform(get("assetservice/rest/v1.0/libraries/search/?collectionIds=418A70D0F31010038152080020F03012&offset=0&limit=1"))

                .andDo(print())
                .andExpect(status().isOk());

    }
}

显示404错误。我期待200.为什么?

如果您看到第二行错误PageNotFound: No mapping found for HTTP request with URI [assetservice/rest/v1.0/libraries/search/] in DispatcherServlet with name ''

是不是因为这个?怎么解决? 错误是:

2017-05-01 20:49:51.252  INFO 13892 --- [           main] s.m.c.LibrarySearchControllerMockMvcTest : Started LibrarySearchControllerMockMvcTest in 3.98 seconds (JVM running for 5.356)
2017-05-01 20:49:51.346  WARN 13892 --- [           main] o.s.web.servlet.PageNotFound             : No mapping found for HTTP request with URI [assetservice/rest/v1.0/libraries/search/] in DispatcherServlet with name ''

MockHttpServletRequest:
      HTTP Method = GET
      Request URI = assetservice/rest/v1.0/libraries/search/
       Parameters = {collectionIds=[418A70D0F31010038152080020F03012], offset=[0], limit=[1]}
          Headers = {}

Handler:
             Type = null

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = null

ModelAndView:
        View name = null
             View = null
            Model = null

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 404
    Error message = null
          Headers = {}
     Content type = null
             Body = 
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

MockHttpServletRequest:
      HTTP Method = GET
      Request URI = assetservice/rest/v1.0/libraries/search/
       Parameters = {collectionIds=[418A70D0F31010038152080020F03012], offset=[0], limit=[1]}
          Headers = {}

Handler:
             Type = null

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = null

ModelAndView:
        View name = null
             View = null
            Model = null

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 404
    Error message = null
          Headers = {}
     Content type = null
             Body = 
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

java.lang.AssertionError: Status 
Expected :200
Actual   :404
 <Click to see difference>


    at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:54)
    at org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:81)
    at org.springframework.test.web.servlet.result.StatusResultMatchers$10.match(StatusResultMatchers.java:664)
    at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:171)
    at com.cdk.dmg.services.mediaasset.controller.LibrarySearchControllerMockMvcTest.testVerifyRetrievedMediaLibrariesJson(LibrarySearchControllerMockMvcTest.java:109)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:237)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

2017-05-01 20:49:51.377  INFO 13892 --- [       Thread-2] o.s.w.c.s.GenericWebApplicationContext   : Closing org.springframework.web.context.support.GenericWebApplicationContext@550dbc7a: startup date [Mon May 01 20:49:48 IST 2017]; root of context hierarchy

Process finished with exit code -1

我的申请类是:

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}

并且代码运行正常。测试时只显示错误。

1 个答案:

答案 0 :(得分:9)

在URL的开头添加斜杠可以解决此问题:

 mvc.perform(get("/assetservice/[...]")

Spring try在尝试将其与端点匹配时可能会按原样获取提供的URL,因此在这种情况下无法找到任何匹配的端点。