#java #unit-testing #mockito #database-connection #dao
Вопрос:
У меня есть класс DAO, методы которого используют соединение, полученное по заданным параметрам
пример
@Override
public boolean insertCarCategory(Connection connection, CarCategory carCategory) throws MySQLEXContainer.MySQLDBExecutionException, SQLException {
int rowNum = 0;
Connection con;
PreparedStatement statement = null;
try{
String query = QueriesUtil.getQuery("insertCarCategory");
con = connection;
statement = con.prepareStatement(query);
statement.setString(1, carCategory.getCarCategory());
statement.setDouble(2, carCategory.getCostPerOneKilometer());
statement.setDouble(3, carCategory.getDiscount());
statement.setBytes(4, ImageUtil.imageToByte(carCategory.getCarCategoryImage()));
rowNum = statement.executeUpdate();
} catch (SQLException e) {
LOGGER.error(e);
throw new MySQLEXContainer.MySQLDBExecutionException("Bad execution",e);
}finally {
ConnectionUtil.oneMethodToCloseThemAll(null,statement,null);
}
return rowNum > 0;
}
У меня есть класс обслуживания, который использует фабрику для получения соединения и передачи его методу Dao, и я протестировал класс обслуживания.Но как я могу протестировать класс Dao?
Ответ №1:
Вы можете протестировать с помощью издевательских объектов, поищите библиотеку Mockito (https://www.tutorialspoint.com/mockito/mockito_overview.htm)
Примерный тестовый случай
Классы Java и тестовый класс с тестовыми случаями
public class CarCategory {
private String carCategory;
private Double costPerOneKilometer;
private Double discount;
private byte[] carCategoryImage;
public CarCategory(String carCategory, Double costPerOneKilometer, Double discount, byte[] carCategoryImage) {
this.carCategory = carCategory;
this.costPerOneKilometer = costPerOneKilometer;
this.discount = discount;
this.carCategoryImage = carCategoryImage;
}
public String getCarCategory() {
return carCategory;
}
public void setCarCategory(String carCategory) {
this.carCategory = carCategory;
}
public Double getCostPerOneKilometer() {
return costPerOneKilometer;
}
public void setCostPerOneKilometer(Double costPerOneKilometer) {
this.costPerOneKilometer = costPerOneKilometer;
}
public Double getDiscount() {
return discount;
}
public void setDiscount(Double discount) {
this.discount = discount;
}
public byte[] getCarCategoryImage() {
return carCategoryImage;
}
public void setCarCategoryImage(byte[] carCategoryImage) {
this.carCategoryImage = carCategoryImage;
}
}
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class CarCategoryDao {
private static final Logger LOGGER = LoggerFactory.getLogger(CarCategoryDao.class);
public boolean insertCarCategory(Connection connection, CarCategory carCategory) throws SQLException {
int rowNum = 0;
Connection con;
PreparedStatement statement = null;
try{
String query = "insertCarCategory";
con = connection;
statement = con.prepareStatement(query);
statement.setString(1, carCategory.getCarCategory());
statement.setDouble(2, carCategory.getCostPerOneKilometer());
statement.setDouble(3, carCategory.getDiscount());
statement.setBytes(4, carCategory.getCarCategoryImage());
rowNum = statement.executeUpdate();
} catch (SQLException e) {
LOGGER.error("sas",e);
throw e;
}
return rowNum > 0;
}
}
import com.dao.utils.CarCategory;
import com.dao.utils.CarCategoryDao;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.springframework.test.context.junit4.SpringRunner;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.when;
@RunWith(SpringRunner.class)
public class CarCategoryDaoTest {
@Mock
private Connection connection;
@Mock
private PreparedStatement statement;
@InjectMocks
private CarCategoryDao carCategoryDao;
@Test
public void test1() throws SQLException {
int actualResponse = 0;
CarCategory cc = new CarCategory("abc", 10.2, 11.1, new byte[100]);
when(connection.prepareStatement(anyString())).thenReturn(statement);
when(statement.executeUpdate()).thenReturn(actualResponse);
boolean result = carCategoryDao.insertCarCategory(connection, cc);
Assert.assertFalse(result);
}
@Test
public void test2() throws SQLException {
int actualResponse = 2;
CarCategory cc = new CarCategory("abc", 10.2, 11.1, new byte[100]);
when(connection.prepareStatement(anyString())).thenReturn(statement);
when(statement.executeUpdate()).thenReturn(actualResponse);
boolean result = carCategoryDao.insertCarCategory(connection, cc);
Assert.assertTrue(result);
}
@Test(expected = SQLException.class)
public void test3() throws SQLException {
int actualResponse = 2;
CarCategory cc = new CarCategory("abc", 10.2, 11.1, new byte[100]);
when(connection.prepareStatement(anyString())).thenReturn(statement);
when(statement.executeUpdate()).thenReturn(actualResponse);
when(statement.executeUpdate()).thenThrow(SQLException.class);
boolean result = carCategoryDao.insertCarCategory(connection, cc);
}
}