2017-07-20 70 views
2

我收到此錯誤信息:java.lang.AssertionError:狀態應爲:200實測值:404

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

我的控制器是這樣

 @Service 
     @RestController 
     @RequestMapping("/execute/files") 
     @ResponseBody 
     public class ControllerFiles { 
      @Autowired 
      @Qualifier("fileRunner") 
      ProcessRunnerInterface processRunnerInterfaceFiles; 

      public InputState executeRestFile(@RequestParam String name) throws ExecutionFailedException, URISyntaxException { 
       ///code///  
      } 
      public List<String>....{ 
      ///code/// 
      } 
     } 

我的測試

@RunWith(SpringJUnit4ClassRunner.class) 
    @SpringBootTest 
    @AutoConfigureMockMvc 
    public class ControllerFilesTest { 

     @Autowired 
     private MockMvc mockMvc; 
     @Autowired 
     ControllerFiles controllerFiles; 

     @Test 
     public void testSpringMvcGetFiles() throws Exception { 

      this.mockMvc.perform(get("/execute/files").param("name", "Spring Community Files")) 
        .andDo(print()).andExpect(status().isOk()); 
     } 
} 

但是,當我有我的代碼這樣的測試工作正常!

  @Service 
      @RestController 
      public class ControllerFiles { 
       @Autowired 
       @Qualifier("fileRunner") 
       ProcessRunnerInterface processRunnerInterfaceFiles; 

       @RequestMapping("/execute/files") 
       @ResponseBody 
       public InputState executeRestFile(@RequestParam String name) throws ExecutionFailedException, URISyntaxException { 
        ///code///   
       } 
       public List<String>....{ 
        ///code/// 
       } 
} 

任何想法是什麼問題呢?

+2

對於初學者刪除'@ Service'(因爲它是一個'@ RestController'不是'@ Service')並刪除'@ ResponseBody',因爲這已經被'@ RestController'所隱含。 –

+0

@ M.Deinum仍然一樣,還有其他建議嗎? –

回答

0

,如果你希望他們被拾起的請求在您的RestController需要的方法被標記爲@RequestMapping資源。如果你想保持在控制器級別,基本要求映射在你的第一個RestController那麼你需要做到以下幾點:

@RestController 
@RequestMapping("my/path") 
public class MyController { 

    @RequestMapping("/") 
    public InputState myMethod() { 
    ... 
    } 
} 
0

因爲它在documentation說:

In the above example, @RequestMapping is used in a number of places. The first usage is on the type (class) level, which indicates that all handler methods in this controller are relative to the /appointments path.

所以類級別@RequestMapping只顯示relativnes。它不是僅基於公共方法聲明實際的資源路徑。所以,你需要註釋你的方法是這樣的:

@GetMapping 
public InputState executeRestFile(@RequestParam String name) throws Exception { 
    // omited 
} 

或者這樣:

@RequestMapping(method = RequestMethod.GET) 
public InputState executeRestFile(@RequestParam String name) throws Exception { 
    // omited 
} 
相關問題