Junit测试数据库连接

时间:2016-08-01 14:02:15

标签: junit4 powermockito

有没有办法测试下面的代码。这是我用JNDI连接到数据库。我是mockito的新手,没有办法测试它。

    @SuppressWarnings("unused")
public Connection getJNDIConnection() {
    Connection result = null;
    try {
        InitialContext initialContext = new InitialContext();
        if (initialContext == null) {
            LOGGER.info("JNDI problem. Cannot get InitialContext.");
        }
        DataSource datasource = (DataSource) initialContext.lookup(jndiName);
        if (datasource != null) {
            result = datasource.getConnection();
        } else {
            LOGGER.info("Failed to lookup datasource.");
        }
    } catch (NamingException ex) {
        LOGGER.error("Cannot get connection: " + ex);
    } catch (SQLException ex) {
        LOGGER.error("Cannot get connection: " + ex);
    }
    return result;
}

1 个答案:

答案 0 :(得分:0)

当然,您可以这样做,但我认为您应该自己阅读文档。这里的要点是:

InitialContext initialContext = mock(InitialContext.class);
DataSource dataSource = mock(DataSource.class);
Connection expected = mock(Connection.class);

whenNew(InitialContext.class).withNoArguments().thenReturn(initialContext);
when(initialContext.lookup(jndiName)).thenReturn(dataSource);
when(initialContext.getConnection()).thenReturn(connection);

Connection result = intatnceOfCalss.getJNDIConnection();

assertSame("Should be equals", expected, result);

此外,您应该使用PowerMock来模拟构造函数和静态方法。要处理Logger,只需添加以下代码:

@BeforeClass
public static void setUpClass() {
    mockStatic(LoggerFactory.class);
    Logger logger = mock(Logger.class);
    when(LoggerFactory.getLogger(ApplySqlFileIfExistsChange.class)).thenReturn(logger);
}

不要忘记注释:

@RunWith(PowerMockRunner.class)
@PrepareForTest({LoggerFactory.class})

尝试阅读此文档http://site.mockito.org/mockito/docs/current/org/mockito/Mockito.html