Home > Blockchain >  Testing a method that returns null at the end
Testing a method that returns null at the end

Time:07-20

public class CustomerDAO implements Dao<Customer> {

public static final Logger LOGGER = LogManager.getLogger();

    @Override
    public Customer modelFromResultSet(ResultSet resultSet) throws SQLException {
        Long id = resultSet.getLong("id");
        String firstName = resultSet.getString("firstName");
        String surname = resultSet.getString("surname");
        return new Customer(id, firstName, surname);
    }
    @Override
    public Customer create(Customer customer) {
        try (Connection connection = DBUtils.getInstance().getConnection();
                PreparedStatement statement = connection
                        .prepareStatement("INSERT INTO customers(firstName, surname) VALUES (?, ?)");) {
            statement.setString(1, customer.getFirstName());
            statement.setString(2, customer.getSurname());
            statement.executeUpdate();
            return readLatest();
        } catch (Exception e) {
            LOGGER.debug(e);
            LOGGER.error(e.getMessage());
        }
        return null;
    }
}

The create method above is the one I am trying to test.

public class CustomerDAOTest {

    private final CustomerDAO DAO = new CustomerDAO();

    @Test
    public void testCreate() {
        final Customer created = new Customer(2L, "chris", "perrins");
        assertEquals(created, DAO.create(created));
    }
}

This is the test I wrote, but obviously the create method will return null, and the created variable won't, therefore the test fails. What can I do to work around this? The original method is not my own code, it's a learning exercise, so ideally I wouldn't want to change it that much if that's a possibility.

CodePudding user response:

Well you could use assertNull:

assertNull(Dao.create(created));

  • Related