我正在嘗試使用來自 mockito 的 when 呼叫來模擬方法的回傳值。但是,我對此很陌生,我可能會誤解 mockito 的作業方式,因為呼叫在呼叫另一個方法時模擬的方法內部呼叫失敗。我想無論該方法是如何實作的,我都應該得到我要求的回傳值?還是我還需要模擬該方法的內部結構?我覺得不應該這樣。
public boolean verifyState(HttpServletRequest request, String s) {
String stateToken = getCookieByName(request, STATE_TOKEN);
String authToken = getCookieByName(request, AUTHN);
boolean isValidState = true;
if (isValidState) {
try {
log.info(getEdUserId(stateToken, authToken));
return true;
} catch (Exception e) {
ExceptionLogger.logDetailedError("CookieSessionUtils.verifyState", e);
return false;
}
} else {
return false;
}
}
public String getEdUserId(String stateToken, String authToken) throws Exception {
String edUserId;
Map<String, Object> jwtClaims;
jwtClaims = StateUtils.checkJWT(stateToken, this.stateSharedSecret); // Failing here not generating a proper jwt token
log.info("State Claims: " jwtClaims);
edUserId = sifAuthorizationService.getEdUserIdFromAuthJWT(authToken);
return edUserId;
}
我的測驗:
@ActiveProfiles(resolver = MyActiveProfileResolver.class)
@WebMvcTest(value = CookieSessionUtils.class, includeFilters = {
@ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, classes = {ApiOriginFilter.class, ValidationFilter.class})})
class CookieSessionUtilsTest {
@Autowired
private CookieSessionUtils cookieSessionUtils; // Service class
@Mock
private CookieSessionUtils cookieSessionUtilsMocked; // Both the method under test and the one mocked are under the same class, so trying these two annotations together.
@Mock
private HttpServletRequest request;
@BeforeEach
public void setUp() {
MockitoAnnotations.initMocks(this);
}
@Test
public void testVerifyState1() throws Exception {
//...Some mocks for getCookieName
UUID uuid = UUID.randomUUID();
when(cookieSessionUtils.getEdUserId(anyString(), anyString()).thenReturn(eq(String.valueOf(uuid))); // When this line runs it fails on verifyState method
assertTrue(cookieSessionUtils.verifyState(request, ""));
}

更新
嘗試使用 anyString() 而不是 eq()。

謝謝你。
uj5u.com熱心網友回復:
錯誤在這里:
when(cookieSessionUtils.getEdUserId(eq("anyString()"), eq("anyString()"))).thenReturn(eq(String.valueOf(uuid)));
它應該讀作
when(cookieSessionUtils.getEdUserId(anyString()), anyString()).thenReturn(uuid);
請參閱Argument matchers 的 Mockito 檔案。
因為尋找字串“anyString()”的引數匹配器永遠不會匹配方法呼叫提供的實際引數,因此永遠不會回傳您期望的 uuid。
uj5u.com熱心網友回復:
你的測驗在幾個地方被破壞了。
設定對真實物體的期望
你應該在模擬和間諜上呼叫 Mockito.when,而不是在被測系統上。Mockito 通常會使用明確的錯誤訊息來報告它,但是您從 中拋出了 NPE getEdUserId,因此會改為報告。NPE 源于這樣一個事實,即 eq 和 anyString 都回傳 null,它被傳遞給 real 方法。
匹配器的無效使用
正如@StefanD 在他的回答中eq("anyString()")所解釋的,不匹配任何字串。它只匹配一個字串“anyString()”
在 WebMvcTest 中混合 Mockito 和 Spring 注釋
這是一個常見的錯誤。Mockito 不會將 bean 注入 spring 背景關系。
從提供的代碼來看,不清楚 CookieSessionUtils 是什么(Controller?ControllerAdvice?)以及測驗它的正確方法是什么。
更新
看來您正在嘗試替換一些正在測驗的方法。一種方法是使用間諜。見https://towardsdatascience.com/mocking-a-method-in-the-same-test-class-using-mockito-b8f997916109
另一種方法是呼叫真正的方法,但模擬所有協作者:StateUtils 和 sifAuthorizationService。如果你想測驗公共 getEdUserId,我可能會選擇這個。
以上幾點仍然有效,在任何一種情況下都需要解決。
由于被測系統是一個服務,我建議放棄 WebMvcTest 并使用普通的 mockito 來測驗它。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/394620.html
上一篇:VisualStudio2022中的測驗資源管理器不起作用
下一篇:設定沒有設定器的模擬類的欄位
