Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to force a SQLException in JUnit
    text
    copied!<p>I'm writing unit tests in JUnit, but have not been able to successfully cover a branch of a particular method that catches a SQLException and returns a null object. This is the class I'm testing:</p> <pre><code>@Component public class UnitOfMeasureRowMapper implements RowMapper&lt;UnitOfMeasure&gt; { public UnitOfMeasure mapRow(final ResultSet resultSet, final int rowNumber) throws SQLException { UnitOfMeasure unitOfMeasure = new UnitOfMeasure(); try { unitOfMeasure.setUnitOfMeasureId(resultSet.getInt("UNITOFMEASUREID")); unitOfMeasure.setOwnerUserId(resultSet.getInt("USERID")); unitOfMeasure.setName(resultSet.getString("NAME")); unitOfMeasure.setDescription(resultSet.getString("DESCRIPTION")); } catch (SQLException e) { unitOfMeasure = null; } return unitOfMeasure; } } </code></pre> <p>This is the JUnit test that I have written to cover the second branch of the above method (with appropriate context from the test class):</p> <pre><code>private static UnitOfMeasure testUnitOfMeasure; private static UnitOfMeasureRowMapper mockRowMapper; public void setUp() throws Exception { mockRowMapper = mock(UnitOfMeasureRowMapper.class); mockResultSet = mock(ResultSet.class); } @Test(expected=SQLException.class) public void testUnitOfMeasureRowMapperFailsSQLException() throws SQLException { when(mockRowMapper.mapRow(mockResultSet, 1)).thenReturn(null); testUnitOfMeasure = mockRowMapper.mapRow(mockResultSet, 1); } </code></pre> <p>I think the problem is with the last line; somehow I need to force a SQLException. The problem is, I don't know how and haven't been able to find an answer. Can anyone help?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload