Skip to content

Extracted duplicated stubbings in UtilTest into a helper - #279

Open
mia-li-001 wants to merge 1 commit into
davidmoten:masterfrom
mia-li-001:refactor-duplicated-stubbings-1
Open

mia-li-001 wants to merge 1 commit into
davidmoten:masterfrom
mia-li-001:refactor-duplicated-stubbings-1

Conversation

@mia-li-001

Copy link
Copy Markdown

I am a researcher at the university. In my analysis of the project, I observed that

In the test class UtilTest, the tests testMapObjectExistingClob and testMapObjectNullClob define the same stubbings:

  • Mockito.when(metaData.getColumnType(1)).thenAnswer(new Answer<Integer>() { @Override public Integer answer(InvocationOnMock invocationOnMock) throws Throwable { return Types.CLOB; } })
  • Mockito.when(resultSet.getObject(1)).thenAnswer(new Answer<Clob>() { @Override public Clob answer(InvocationOnMock invocationOnMock) throws Throwable { return getClobAnswerValue; } })
  • Mockito.when(resultSet.getClob(1)).thenAnswer(new Answer<Clob>() { @Override public Clob answer(InvocationOnMock invocationOnMock) throws Throwable { return getClobAnswerValue; } })
  • Mockito.when(resultSet.getMetaData()).thenAnswer(new Answer<ResultSetMetaData>() { @Override public ResultSetMetaData answer(InvocationOnMock invocationOnMock) throws Throwable { return metaData; } })

Here metaData, resultSet and getClobAnswerValue stand for the values that differ from test to test.

These duplicated stubbings repeat the setup in each test, so a change to that setup has to be made in 2 places. I propose extracting them into 1 private helper method:

  • setupResultSetGetClobAndGetMetaDataAndGetColumnTypeAnd1MoreStubs, which takes 3 parameters (metaData, resultSet and getClobAnswerValue) and is called from 2 tests.

This refactoring also reduces the cognitive complexity of UtilTest by 7.5% (from 401.5 to 371.4, measured with Genese). Cognitive complexity, introduced by SonarSource, estimates how hard code is for a human to understand.

The change only moves the existing stubbings into the helper. The stubbed calls, arguments and returned values are the same as before, and the test results are unchanged.

I propose a solution below to remove the duplicated stubbings. Happy to modify the pull request based on your feedback.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant