【发布时间】:2020-12-18 05:12:03
【问题描述】:
我有以下代码
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class DatabaseReader {
public static final String CONNECTION = "jdbc:mysql://localhost/testdb";
public static String getById(Integer id) throws SQLException {
String query = "SELECT * FROM Foo WHERE Id = ?";
Connection connection = DriverManager.getConnection(CONNECTION);
PreparedStatement preparedStatement = connection.prepareStatement(query);
preparedStatement.setInt(1, id);
ResultSet resultSet = preparedStatement.executeQuery();
resultSet.next();
String result = resultSet.getString(0);
resultSet.close();
preparedStatement.close();
connection.close();
return result;
}
public static String getId(int id) throws SQLException{
return getById(id);
}
}
是否可以对函数 getById 进行 powermock,以便在测试 getId 时获得 getById 的模拟值? 我正在尝试这个:
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.when;
import static org.powermock.api.mockito.PowerMockito.mockStatic;
import static org.powermock.api.mockito.PowerMockito.verifyStatic;
import java.sql.SQLException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
@RunWith(PowerMockRunner.class)
@PrepareForTest(DatabaseReader.class)
public class DatabaseReaderTest {
@Test
public void testGetById() {
int inputId = 1;
String returnValue = "JavaCodeGeeks";
mockStatic(DatabaseReader.class);
try {
when(DatabaseReader.getById(inputId))
.thenReturn(returnValue);
String actual = DatabaseReader.getId(inputId);
System.out.println(actual);
verifyStatic();
assertEquals(returnValue, actual);
} catch (SQLException e) {
fail("No exception should be thrown.");
}
}
但是,当我打电话时它不起作用
String actual = DatabaseReader.getId(inputId);
它尝试调用整个数据库方法。 我对 IU 是否可以从静态方法模拟静态方法调用感到困惑。
【问题讨论】:
-
getId 是一个非常简单的方法,我不会费心去测试它。另一方面,如果 executeQuery 抛出异常,最好进行测试以检查 getById 是否不会泄漏连接。
-
我想了解我们是否可以使用 powermock api 测试从另一个静态方法内部调用的静态方法。
-
请将您的导入添加到您问题中的测试代码中。
标签: java junit mocking mockito powermock