我正在嘗試測驗一個呼叫另一個方法的方法,該方法使用行內初始化的私有最終靜態變數。然后我嘗試在測驗運行時更改變數的值。我一直在嘗試諸如 spring 反射或為該特定領域添加 setter 之類的東西,但也許我應該使用一些我以前從未使用過的作為 powermock 的東西。我正在自己嘗試實作這一點,沒有人問,所以我是否可以就最好的繼續進行方式提供一些指導。
更新
根據我在這里得到的一些反饋,模擬私有最終變數可能不是我應該為我的測驗做的事情。我在這里打開了一個不同的問題Mock return value for cookie.getValue() using Mockito
@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 "";
}
這些是我嘗試過的一些事情:
@Autowired
private CookieSessionUtils cookieSessionUtils;
@Mock
private HttpServletRequest request;
@Test
public void testVerifyState() {
Cookie mockCookie = Mockito.mock(Cookie.class);
Mockito.when(mockCookie.getName()).thenReturn("YviaductLocalAmp");
Mockito.when(request.getCookies()).thenReturn(new Cookie[]{mockCookie});
// cookieSessionUtils.setViaductLocalAmp("YviaductLocalAmp");
// setField(cookieSessionUtils, "VIADUCT_LOCAL_AMP", VIADUCT_LOCAL_AMP);
// Mockito.when(cookieSessionUtils.getCookieByName(request, "YviaductLocalAmp")).thenReturn("Y");
assertTrue(cookieSessionUtils.verifyState(httpServletRequest, "viaductLocalAmp"));
}
謝謝你。
uj5u.com熱心網友回復:
不確定 Powermock 是否能夠提供幫助。
推薦的方法是不要使用在測驗時需要更改的行內常量。
- 如果你想改變這一點,你需要在兩者之間引入一個提供常量的介面。將它的一種實作用于實際源,另一種用于測驗。測驗時切換實作。
如果你不想改變這一點,你可以嘗試下面的反射方法
- 使該欄位可訪問。
- 洗掉最終修飾符
- 編輯欄位值
我從這個討論中得到了這個建議
private static void setFinalStatic(Field field, Object newValue) throws Exception {
Field field = ClassWhereToMockStaticFinalVar.class.getDeclaredField("FieldName");
field.setAccessible(true);
// remove final modifier from field
Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
field.set(null, newValue);
}
uj5u.com熱心網友回復:
您試圖違反資訊隱藏/封裝原則,因為您正在嘗試“測驗代碼”。
但是 UnitTests 不會“測驗代碼”。
單元測驗驗證公共可觀察 行為,即:回傳值和與依賴項的通信。
該常量的實際內容是測驗不應該關心的實作細節。
因此,您真正應該測驗的是,如果請求包含名稱為“viaductLocalAmp”且值為“Y”的 cookie ,則verifyState()回傳。true
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/391803.html
上一篇:測驗答案檢查器時出現型別錯誤
