簡體   English   中英

錯誤模擬 @Inject 類 JUnit Mockito

[英]Error mocking @Inject classes JUnit Mockito

我在使用 JUnit 和 Mockito 時遇到了一些麻煩。 首先,我給你我所擁有的所有信息。

JWTValidator.java

@Inject
JWTUtils jwtUtils;

public void validateJWT(String jwt) { //The main function returns true, false or an exception
[...]
Claims claims = jwtUtils.getClaims(jwt); //claims = null here!
[...]
}

JWTUtils.java

public void getClaims(jwt) { //This should return an Exception with the JWT that I use on the JWTTestServlet.java
[...]
}

JWTTestServlet.java

@InjectMocks
private JWTValidator jwtValidator;
        
@Mock
private JWTUtils jwtUtils;

@Before
public void setup() throws Exception {
    MockitoAnnotations.initMocks(this);
}

@Test(expected=Exception.class)
public void testJWTWithoutGUID() {
final String jwt = ""; //Some JWT 
    String message = "";
    try {
        jwtValidator.validateJWT(jwt);
    } catch (Exception e) {
        message = e.getMessage();
        System.out.println(message);
    }
    assertTrue(message.contains(MSG_WITHOUT_GUID));
}

關鍵是當我調用JWTUtils 的 getClaims函數時,它不起作用,我收到一個空字段。 我嘗試了許多不同的注釋,但它也不起作用。 JWTUtils 為 null 或函數返回 null。

我可以調試 JWTValidator 但我不能調試 JWTUtils。

你能幫我么?

非常感謝 最好的問候

解決了! 解決方案是我必須定義模擬類的行為(JWTUtils)

when(jwtUtils.getJWTClaims(jwt)).thenReturn(new DefaultClaims());

現在當我調用這個函數時,我沒有空對象。

非常感謝!

默認情況下,模擬的所有方法都返回“未初始化”或“空”值,例如,數字類型(原始和裝箱)為零,布爾值為假,大多數其他類型為空。

我認為您需要的不是 Mock 而是間諜: 使用 Mockito 存根和執行測試方法

暫無
暫無

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

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