Тестирование PreparedStatement и Connection с помощью Mockito

267
07 января 2018, 06:38

Помогите, пожалуйста протестировать класс с помощью моков

@Slf4j
public class PreparedStatementBuilder implements AutoCloseable {
private final static ResourceBundle resourceBundle = ResourceBundle.getBundle("database/mysql");
private final static String HOST = resourceBundle.getString("HOST");
private final static String USER = resourceBundle.getString("USER");
private final static String PASS = resourceBundle.getString("PASS");
private PreparedStatement preparedStatement;
private Connection connection;
PreparedStatementBuilder(String sql) {
    PreparedStatement preparedStatement = null;
    LOGGER.debug("init PrepareStatementBuilder");
    try {
        preparedStatement = createConnection().prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
    } catch (SQLException e) {
        e.printStackTrace();
        LOGGER.error(e.getMessage(), e);
    }
    this.preparedStatement = preparedStatement;
}
Connection createConnection() throws SQLException {
    MysqlDataSource dataSource = new MysqlDataSource();
    dataSource.setUser(USER);
    dataSource.setPassword(PASS);
    dataSource.setURL(HOST);
    LOGGER.debug("create connection");
    connection = dataSource.getConnection();
    return connection;
}
public PreparedStatement getPreparedStatement() {
    return preparedStatement;
}
@Override
public void close() {
    if (connection != null) {
        try {
            connection.close();
            LOGGER.debug("close connection");
        } catch (SQLException e) {
            e.printStackTrace();
            LOGGER.error(e.getMessage(), e);
        }
    }
    if (preparedStatement != null) {
        try {
            preparedStatement.close();
            LOGGER.debug("close preparedStatement");
        } catch (SQLException e) {
            e.printStackTrace();
            LOGGER.error(e.getMessage(), e);
        }
    }
}
}

никак не получается осознать логику мокирования

public class PreparedStatementBuilderTest {
private final static ResourceBundle resourceBundle = ResourceBundle.getBundle("database/mysql");
private final static String HOST = resourceBundle.getString("HOST");
private final static String USER = resourceBundle.getString("USER");
private final static String PASS = resourceBundle.getString("PASS");
@Mock
MysqlDataSource dataSource;
@Mock
Connection connection;
@Spy
PreparedStatement preparedStatement;
@Mock
PreparedStatementBuilder preparedStatementBuilder;
@Mock
private Statement mockStatement;
@Before
public void init(){
    MockitoAnnotations.initMocks(this);
}
@Test
public void createdPreparedStatementTest() throws SQLException {
    preparedStatementBuilder = new PreparedStatementBuilder(anyString());
    dataSource.setUser(USER);
    dataSource.setPassword(PASS);
    dataSource.setURL(HOST);
    when(dataSource.getConnection()).thenReturn(connection);
    when(connection.prepareStatement(anyString(), anyInt())).thenReturn(preparedStatement);
    verify(connection, times(1)).prepareStatement(anyString(), anyInt());
    verify(connection, times(1)).close();
    verify(preparedStatement, times(1)).close();
    assertTrue(connection.isClosed());
    assertTrue(preparedStatement.isClosed());
}
}

буду благодарен за пример теста

READ ALSO
Чтение русского текста из File

Чтение русского текста из File

Задача: скачать текст из Firebase и продемонстрировать его в log'ах

272
Libgdx “затухающая” анимация

Libgdx “затухающая” анимация

Имеется кнопка TextButton , так же есть анимация spinAnimationНи как не могу понять, как реализовать "затухание анимации"(т

266
Как перебрать циклом массив для поиска совпадений?

Как перебрать циклом массив для поиска совпадений?

Пишу свою первую игру по типу три в ряд! В процессе создания игры сделал следующее:

291
Js + Java EE(Ajax добавление данных в таблицу)

Js + Java EE(Ajax добавление данных в таблицу)

Здравствуйте, есть приложение, в котором находится комната администратораТам есть таблица в которой находятся группы студентов, и есть кнопочка...

250