如何为 junit 测试模拟 resultmetadata
how to mock resultmetadata for junit testing
有一项功能使用结果元数据。
ResultSet rs // coming from some sql query.
ResultSetMetaData rsmd = rs.getMetaData();
if(rsmd.getColumnName(1).toString().equalsIgnoreCase("something"))
{
//do something here
}
我以前模拟过结果集,但不知道如何模拟结果元数据或将所需的列名放入结果集中?
我试过了:
ResultSetMetaData rsmd = Mockito.mock(ResultSetMetaData.class);
Mockito.when(rsmd.getColumnName(1)).thenReturn("Somwthing");
但是没用
这是您需要执行的操作的示例:
import org.mockito.Mockito;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.when;
public class Test {
@org.junit.Test
public void test() throws SQLException {
// prepare the dependant mock
ResultSetMetaData rsMetaMock = Mockito.mock(ResultSetMetaData.class);
when(rsMetaMock.getColumnName(eq(1))).thenReturn("something");
// prepare main mock for result set and define when
// main mock to return dependant mock
ResultSet rs = Mockito.mock(ResultSet.class);
when(rs.getMetaData()).thenReturn(rsMetaMock);
// application logic
ResultSetMetaData rsmd = rs.getMetaData();
//assertions
assertEquals(rsmd.getColumnName(1), "something");
}
}
有一项功能使用结果元数据。
ResultSet rs // coming from some sql query.
ResultSetMetaData rsmd = rs.getMetaData();
if(rsmd.getColumnName(1).toString().equalsIgnoreCase("something"))
{
//do something here
}
我以前模拟过结果集,但不知道如何模拟结果元数据或将所需的列名放入结果集中? 我试过了:
ResultSetMetaData rsmd = Mockito.mock(ResultSetMetaData.class);
Mockito.when(rsmd.getColumnName(1)).thenReturn("Somwthing");
但是没用
这是您需要执行的操作的示例:
import org.mockito.Mockito;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.when;
public class Test {
@org.junit.Test
public void test() throws SQLException {
// prepare the dependant mock
ResultSetMetaData rsMetaMock = Mockito.mock(ResultSetMetaData.class);
when(rsMetaMock.getColumnName(eq(1))).thenReturn("something");
// prepare main mock for result set and define when
// main mock to return dependant mock
ResultSet rs = Mockito.mock(ResultSet.class);
when(rs.getMetaData()).thenReturn(rsMetaMock);
// application logic
ResultSetMetaData rsmd = rs.getMetaData();
//assertions
assertEquals(rsmd.getColumnName(1), "something");
}
}