簡體   English   中英

Mockito.when() 在模擬 Autowired 對象時無法正常工作

[英]Mockito.when() not working properly while mocking Autowired object

我有一個控制器類,我可以在其中獲取有關當前登錄用戶的詳細信息。 方法名稱是LoggedInUser() 該方法總體上運行良好,但我無法為特定方法生成單元測試用例。

為了測試它,我正在使用 Mockito 但Mockito.when()無法正常工作。 我經歷了所有相關的問題,但無法解決它。

以下是我到目前為止所做的。

控制器.java

    @Service
    @Transactional
    Public class Controller implements someInterface {

private LoggedInUser getUser(HttpServletRequest request) {
            principal = request.getUserPrincipal();
            Authentication tk = (Authentication) principal;
            //Authentication tk = (Authentication)(request.getUserPrincipal());
            LoggedInUser user = (LoggedInUser) tk.getPrincipal();
            return user;
        }

評論中的這一行是因為我在另一篇文章中讀到它可能無法正常工作,因為 'principal' 再次實例化。 所以我試圖繞過它,但這並沒有奏效。

測試.java

@Mock
    private HttpServletRequest httpServletRequest;

public void tes() {
        //httpServletRequest = Mockito.mock(HttpServletRequest.class);
        Principal principal= Mockito.mock(Principal.class);
        Mockito.when(httpServletRequest.getUserPrincipal()).thenReturn(principal);
.......
.......
}

在調試時,我正在獲取request (object of HttpServletRequest)值,因為它在控制器類中自動裝配,但principal始終為空。 任何幫助將不勝感激!!

你在這個測試類上添加了@RunWith(MockitoJUnitRunner.class)嗎? 因為只有這樣@Mock才會起作用。 我假設您將模擬的HttpServletRequest傳遞給getUser()

您尚未注入httpServletRequest對象httpServletRequest 您需要將此模擬對象傳遞給您的getUser方法進行測試。

我無法模擬HttpServletRequest ,因為它的Autowired ,從而request.getUserPrincipal()始終保持為空,因為它永遠不會調用mock().when方法。 我以以下方式替換了代碼,它起作用了!!

控制器.java

    @Service
    @Transactional
    Public class Controller implements someInterface {

    public LoggedInUser getUser() {
        LoggedInUser user = (LoggedInUser )SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        return user;
    }

測試.java

    @Mock
    private Principal principal;

    @Mock
    private SecurityContext securitycontext;

    @Mock
    private Authentication authentication;
     public void test() {
      LoggedInUser user = new LoggedInUser();
        Mockito.when(authentication.getPrincipal()).thenReturn(user);
        Mockito.when(securitycontext.getAuthentication()).thenReturn(authentication);
        SecurityContextHolder.setContext(securitycontext);
.......
.......
}

暫無
暫無

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

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