![](/img/trans.png)
[英]Mocking Local Scope Objects using Powermock and mockito within a static method
[英]Mocking methods of local scope objects with Mockito2.7
我們在我們的項目中使用Maven,Jersey和Mockito 2。 具有PowerMockito 1.7.4依賴性的Mockito 2.7.5引起了一些問題:無法模擬本地范圍變量的方法。 這是我的示例代碼:
import com.fasterxml.jackson.databind.ObjectMapper;
public Class Sample{
public String method1(String input){
ObjectMapper mapper = new ObjectMapper();
InputDO inputDO = mapper.readValue(input, InputDO.class);
}
}
Inside Test Class
@Test
public void testMethod(){
ObjectMapper mapper = Mockito.mock(ObjectMapper.class);
InputDO = inputDO = Mockito.mock(InputDO.class);
doReturn(inputDO).when(mapper).readValue(anyString(), eq(InputDO.class));
Sample s = Mockito.mock(Ssample.class);
s.method1(anyString());
assertNotNull(s);
}
測試在mapper.raedValue()中失敗。 請幫助我嘲笑上述步驟。
測試失敗,因為您在測試類中為ObjectMapper創建了一個模擬,但是在這里每次每次使用new關鍵字創建新的ObjectMapper時。 這樣會更好
`class Test{
ObjectMapper ObjectMapperMock = new ObjectMapper();
ObjectMapper spymapper=spy(ObjectMapperMock);
doReturn(result).when(spymapper.readValue());
}
`
確保你:
1)注釋測試類:
@RunWith(PowerMockRunner.class)
@PrepareForTest(ObjectMapper.class)
2)將其添加為測試方法的第一行:
ObjectMapper mapper = Mockito.mock(ObjectMapper.class);
PowerMockito.whenNew(ObjectMapper.class).withNoArguments().thenReturn(mapper);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.