有一个关于在 Junits 中检查已处理异常的问题。我似乎在我的代码中做到了这一点。其他人倾向于说这是不可能的,因为该方法没有抛出异常。有人可以解释下面的代码中发生了什么。
public class DatabaseConnector
{
private DBConnectionInfo dbObject;
private DBQueryStatements dbQueries;
void loadConnectionInfo()
{
Properties databaseProperties = new Properties();
try
{
databaseProperties.load(getClass().getClassLoader().getResourceAsStream("database.properties"));
dbObject.setDatabaseURL(databaseProperties.getProperty("jdbc.url"));
dbObject.setUserName(databaseProperties.getProperty("jdbc.username"));
dbObject.setPassword(databaseProperties.getProperty("jdbc.password"));
dbObject.setDriver(databaseProperties.getProperty("jdbc.driver"));
} catch (IOException e)
{
Logger lgr = Logger.getLogger(PostgreLocationManager.class.getName());
lgr.log(Level.SEVERE, e.getMessage(), e);
}
}
public DBConnectionInfo connectionInit()
{
loadConnectionInfo();
try
{
Class.forName(dbObject.getDriver());
} catch (Exception e)
{
Logger lgr = Logger.getLogger(PostgreLocationManager.class.getName());
lgr.log(Level.SEVERE, e.getMessage(), e);
}
try
{
dbObject.setConnection(DriverManager.getConnection(dbObject.getDatabaseURL(), dbObject.getUserName(),
dbObject.getPassword()));
} catch (Exception e)
{
Logger lgr = Logger.getLogger(PostgreLocationManager.class.getName());
lgr.log(Level.SEVERE, e.getMessage(), e);
}
return dbObject;
}
}
上述代码的测试用例。
public class DatabaseConnectorTest
{
DatabaseConnector dbConnector;
DBConnectionInfo dbModelObject;
DBQueryStatements dbQueries;
@Before
public void setUp() throws Exception
{
MockitoAnnotations.initMocks(this);
dbModelObject = mock(DBConnectionInfo.class);
dbQueries = mock(DBQueryStatements.class);
dbConnector = new DatabaseConnector(dbModelObject,dbQueries);
}
@Test
public void testDriverFailure()
{
when(dbModelObject.getDriver()).thenReturn("driver");
when(dbModelObject.getDatabaseURL()).thenReturn("jdbc:postgresql://127.0.0.1:5432/testdb");
when(dbModelObject.getUserName()).thenReturn("postgres");
when(dbModelObject.getPassword()).thenReturn("postgres");
try
{
dbConnector.connectionInit();
} catch (Exception e)
{
assertTrue(e instanceof ClassNotFoundException);
}
verify(dbModelObject).getDriver();
}
@Test
public void testConnectionFailure()
{
when(dbModelObject.getDriver()).thenReturn("org.postgresql.Driver");
when(dbModelObject.getDatabaseURL()).thenReturn("jdbc:postgresql://127.0.0.1:5432/testdb");
when(dbModelObject.getUserName()).thenReturn("uname");
when(dbModelObject.getPassword()).thenReturn("uname");
try
{
dbConnector.connectionInit();
} catch (Exception e)
{
assertTrue(e instanceof SQLException);
}
verify(dbModelObject).getDriver();
verify(dbModelObject).getDatabaseURL();
verify(dbModelObject).getUserName();
verify(dbModelObject).getPassword();
}
}