簡體   English   中英

在Spring Boot中測試Rest API時,Spring Test返回404而不是200

[英]Spring Test returning 404 instead of 200 in testing Rest API in Spring Boot

簡單來說,我的控制器是這樣的:

@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 ''看到第二行錯誤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);
    }

}

和代碼運行正常。 測試時僅顯示錯誤。

在URL的開頭添加斜杠將解決此問題:

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

當嘗試將其與端點匹配時,Spring測試可能會按原樣獲取提供的URL,因此在這種情況下找不到任何匹配的端點。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM