I am trying to mock the getMeasureAggregator() of ResultSetRow object - I don't seem to succeed. I am very new in writing mockito unit test.
I want the BuilSQL.formatMeasuer() goes to case 2: so what I have decided to do was mocking row.getMeasureAggregator.
Here is my BuildSQL class:
public class SQLBuilder { public static String buildSQL(JsonObject requestData, JsonObject queryInfo) throws AcquisitionException { JsonArray jArray = queryInfo.get("columns").getAsJsonArray(); Set<String> columns = new HashSet<>(jArray.size()); for (int i = 0; i < jArray.size(); i++) { columns.add(jArray.get(i).getAsString()); } List<ResultSetRow> selectedRows = new ArrayList<>(); List<ResultSetRow> retrievedRows = null; retrievedRows = MetaDataProvider.executeMetadataRequest(queryInfo, requestData); // this method returns a collection of RetrievedResultSetRow for (ResultSetRow retrievedRow: retrievedRows) { if (//some condition evaluates to true) { selectedRows.add(retrievedRow); } } String sql = ""; String select = "SELECT "; for (int i = 0; i < selectedRows.size(); i++) { ResultSetRow row = selectedRows.get(i); select += formatMeasure(row.getMeatureName(), row.getMeasureAggregator()); } select = select.substring(0, select.length() - 1); return sql; } private static String formatMeasure(String measureName, int measureAggregator) { switch(measureAggregator) { case 1: return "sum(\"" + measureName + "\")" + " AS \"" + measureName + "\","; case 2: return "COUNT(\"" + measureName + "\")" + " AS \"" + measureName + "\","; return measureName; } } here is my ResultSetRow class:
public class ResultSetRow { private final int iRow; private final int measureAggregator; public ResultSetRow(JsonObject dimensionMetadata) { this.iRow = dimensionMetadata.get("ROW").getAsInt(); this.measureAggregator = dimensionMetadata.get("MEASURE_AGGR").getAsInt(); } public int getMeasureAggregator() { return measureAggregator; } } here is how I am mocking
@RunWith(PowerMockRunner.class) @PrepareForTest({ HanaClientRequestUtils.class, RetrievedResultSetRow.class }) public class HanaSQLBuilderTest { private ResultSetRow resultSetRow; private requestData; private queryInfo @Test public void formatMeatureExecuteCase2() throws Exception{ resultSetRow = Mockito.mock(ResultSetRow.class); PowerMockito.when(resultSetRow.getMeasureAggregator()).thenReturn(2); String querySQL = HanaSQLBuilder.buildSQL(requestData, queryInfo); System.out.println(querySQL); } } } I am not sure why row.getMeasureAggregator() does not return 2?
MetaDataProvider.executeMetadataRequest(...)method the exact object what You mock in Your test. Otherwise the ResultSetRow instances are not mocked by Mockito.MetaDataProvider.executeMetadataRequestso it returns a list of your mockedResultSetRows. But because this method is static, Mockito can have problems mocking it (PowerMock can mock static methods as I know, but please check it).