我正在嘗試測驗由另一種方法使用的 getCookieByName 方法。但是,不確定我是否正確執行此操作,因為該方法似乎被多次呼叫,并且它在第一次嘗試時設定了值,但在最后一次呼叫時為空。我認為模擬呼叫的順序可能是錯誤的,或者其中一些可能不需要,但是如果我洗掉了任何內容,我仍然會遇到其他錯誤,所以不確定我實際上做錯了什么。
@Service
public class CookieSessionUtils {
private static final String VIADUCT_LOCAL_AMP = "viaductLocalAmp"; // Value to be changed when the test runs to test the "if Y" scenario.
public boolean verifyState(HttpServletRequest request, String state) {
String viaductLocalAmp = getCookieByName(request, VIADUCT_LOCAL_AMP);
if (viaductLocalAmp.equalsIgnoreCase("Y")) {
return true;
}
return false;
}
public String getCookieByName(HttpServletRequest request, String cookieName) {
try {
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals(cookieName)) {
return cookie.getValue();
}
}
}
} catch (Exception e) {
ExceptionLogger.logDetailedError("CookieSessionUtils.getCookieByName", e);
log.error("Error on Cookie " e.getMessage());
}
return "";
}
這些是我的測驗和模擬呼叫,以及在同一方法中呼叫 getCookieByName() 的兩次。
@Autowired
private CookieSessionUtils cookieSessionUtils;
@Mock
private HttpServletRequest request;
@Test
public void testVerifyStateWhenCookieNameStartsWithY() {
Cookie mockCookie = Mockito.mock(Cookie.class);
when(mockCookie.getName()).thenReturn("viaductLocalAmp");
when(mockCookie.getValue()).thenReturn("viaductLocalAmp");
when(request.getCookies()).thenReturn(new Cookie[]{mockCookie});
when(cookieSessionUtils.getCookieByName(request, "viaductLocalAmp")).thenReturn("Y");
assertTrue(cookieSessionUtils.verifyState(httpServletRequest, "viaductLocalAmp"));
}


謝謝你。
uj5u.com熱心網友回復:
我在斷言下使用了錯誤的物件。@httpRequest 用@MockBean 注釋,而請求使用@Mock,這是我應該在這個場景中使用的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/401312.html
上一篇:運行時分叉的快板單元測驗崩潰
