0
我是JUNITS的新手,一直試圖使用Mockito和PowerMockito爲我的代碼編寫一些測試用例,但一直面臨一個問題。無法模擬方法
類代碼:
public class Example implements Callable<Void> {
int startIndex;
int endIndex;
ConnectionPool connPool;
Properties properties;
public Example(int start, int end,
ConnectionPool connPool, Properties properties) {
this.startIndex = start;
this.endIndex = end;
this.connPool= connPool;
this.properties = properties;
}
@Override
public Void call() throws Exception {
long startTime = System.currentTimeMillis();
try {
List<String> listInput = new ArrayList<>();
Service service = new Service(
dbConnPool, properties, startIndex, endIndex);
service.getMethod(listInput);
.
.
.
JUNIT代碼:
@RunWith(PowerMockRunner.class)
@PrepareForTest()
public class ExampleTest {
@Mock
private ConnectionPool connectionPool;
@Mock
private Properties properties;
@Mock
private Service service = new Service(
connectionPool, properties, 1, 1);
@Mock
private Connection connection;
@Mock
private Statement statement;
@Mock
private ResultSet resultSet;
@InjectMocks
private Example example = new Example(
1, 1, connectionPool, properties);
@Test
public void testCall() throws Exception {
List<String> listInput= new ArrayList<>();
listInput.add("data1");
when(service.getMethod(listInput)).thenReturn(listInput);
example.call();
}
問題:如何模擬服務類和它的方法,getMethod,打電話?
說明:Service類具有方法getMethod,它與數據庫交互。所以,因爲我無法嘲笑這個方法,所以代碼會經過,然後我必須將getMethod中的所有對象作爲連接,結果集等進行嘲諷。否則會拋出NullPointerException。
請幫我理解我做錯了什麼,如果可能的話,請提供你的指導,告訴我應該如何處理這種方法調用的JUNITS。
該PowerMock與EasyMock,但我使用mockito PowerMockito。 我試過了:Service mockService = PowerMockito.mock(Service.class); PowerMockito.whenNew(Service.class,connectionPool,properties,1,1) .andReturn(mockService);這是拋出錯誤。有什麼建議麼? –
@AyushKumar你能否顯示你得到的錯誤? –
它顯示了一個語法錯誤。 我試過了你提供的另一種解決方案,但它並沒有模擬方法調用,而是依然流經。 –