我想做一些JUnit测试,但是我在连接数据库时遇到了问题。
我想测试方法:getAndSavePlant
public class App
{
private static Connection connection = null;
public static void main( String[] args )
{
try {
Class.forName("com.mysql.jdbc.Driver");
log.info("Le driver MySQL JDBC est bien enregistré.");
} catch (ClassNotFoundException e) {
log.info("Erreur, le driver JDBC est introuvable. Assurez-vous d'avoir ajouter le driver JDBC aux dépendances Maven correctement. ", e);
return;
}
try {
connection = DriverManager.getConnection("databaseUrl", "user", "password");
log.info("La connexion à la base de données a réussi. (" + connection.getMetaData().getURL() + ")");
} catch (SQLException e) {
log.error("La connexion à la base de données a échoué ! (" + connection.getMetaData().getURL() + ")");
throw new SQLException();
}
getAndSavePlant();
}
public static void getAndSavePlant() {
if(...)
getFruitName("1");
else if(...)
getTreeName("4");
else if(...){
getFlowerName("7");
saveRecord(values);
}
}
例如getFruitName()
:
public static String getFruitName(String idFruit) {
try (PreparedStatement pstmt = connection.prepareStatement("SELECT name FROM fruit WHERE id = ?")) {
pstmt.setInt(1, Integer.parseInt(idFruit));
try (ResultSet rs = pstmt.executeQuery()) {
if(rs.next())
return rs.getString("name");
else
return null;
}
} catch (SQLException e) {
log.error("getFruitName => SQL Exception" ,e);
return null;
}
}
但是connection
对象存在问题null
。
所以我尝试使用以下代码模拟getAndSavePlant
中包含的方法:
@Test
public void testGetAndSaveFruit(){
try {
PowerMockito.mockStatic(App.class);
PowerMockito.when(App.class, "getFruitName", "1").thenReturn("Apple");
PowerMockito.when(App.class, "getFruitName", "7").thenReturn("Strawberry");
PowerMockito.when(App.class, "getTreeName", "2").thenReturn("pine");
PowerMockito.when(App.class, "getTreeName", "4").thenReturn("oak");
PowerMockito.when(App.class, "getFlowerName", "1").thenReturn("Rose");
PowerMockito.when(App.class, "getFlowerName", "4").thenReturn("orchid");
App.getAndSavePlant();
} catch (IOException e) {
e.printStackTrace();
Assert.fail("Error");
} catch (Exception e) {
e.printStackTrace();
}
}
但是对getAndSavePlant
的调用什么也没做。
我怎么能只在内部调用静态方法?