2017-08-27 128 views
2

我試着創建我的第一個測試簡單的彈簧引導控制器,但我得到Handler: Type = null。在瀏覽器中,代碼是可行的,但測試失敗。我的應用程序使用spring-security。請幫我解決一個問題並理解我的錯誤。謝謝。爲什麼春季測試失敗,不起作用@MockBean

這是控制器:

private final ItemService service; 

@GetMapping("/get_all_items") 
public String getAllItems(Model model) { 
    model.addAttribute("items", service.getAll()); 
    return "all_items"; 
} 

這是一個測試。

@RunWith(SpringRunner.class) 
@WebMvcTest(ItemController.class) 
public class ItemControllerTest { 

    @Autowired 
    private MockMvc mvc; 

    @MockBean 
    private ItemService itemService; 

    @Test 
    @WithMockUser(username = "user", roles = "user")//mock security. 
    public void whenGetAllItemsThenControllerReturnAllItems() throws Exception { 
     given(
      itemService.getAll() 
     ).willReturn(
       new ArrayList<Item>() 
     ); 

     mvc.perform(
      get("/get_all_items").accept(MediaType.TEXT_HTML) 
     ).andExpect(
       status().isOk() 
     ); 
    } 
} 

這是結果日誌:

MockHttpServletRequest: HTTP Method = GET Request URI = /get_all_items Parameters = {} Headers = {Accept=[text/html]}

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 = 403 Error message = Access is denied Headers = {X-Content-Type-Options=[nosniff], X-XSS-Protection=[1; mode=block], Cache-Control=[no-cache, no-store, max-age=0, must-revalidate], Pragma=[no-cache], Expires=[0], X-Frame-Options=[DENY], Strict-Transport-Security=[max-age=31536000 ; includeSubDomains]} Content type = null Body = Forwarded URL = null Redirected URL = null Cookies = []

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

+0

您是否嘗試過'@ MockMvc'?有一些變化嗎? – Reborn

+0

錯誤就在那裏。 ':狀態= 403錯誤消息=訪問被拒絕標題。您需要提供安全聲明,或者禁用它以進行單元測試。 –

+0

@Darren Forsythe是的,但我使用'@WithMockUser(username =「user」,roles =「user」)'這是不夠的?如何實施提供安全信用?我想我的@WithMockUser解決。 – Pavel

回答

1

這基本上是已經在這裏找到答案重複的問題:https://stackoverflow.com/a/38676144/388980

的解決方案是進口@Configuration類爲您的春季安全配置除了像這樣聲明@WebMvcTest(ItemController.class)@Import(SecurityConfig.class)(假設您的Spring Security的自定義配置位於名爲的類中)。

您也可能會發現在春季啓動的問題跟蹤器的討論有所幫助,以及:https://github.com/spring-projects/spring-boot/issues/6514

的另一種選擇是禁用春季安全作爲解釋在這裏:Disable security for unit tests with spring boot

+0

我的錯誤@WithMockUser(username =「user」,roles =「user」) - > @ WithMockUser(username =「user」,roles =「USER」)需要轉換角色「user」CAPSLOOK。一切都好。 – Pavel