我正在使用Mockito来模拟我的JUnit测试类中的类,如下所示:
@Before
public void initialize(){
DescribeHiveTable mockObj = Mockito.mock(DescribeHiveTable.class);
String tableName = "clslog_assessments";
String parentDirectoryPath ="src/test/resources/TEST18/RunFiles";
String[] mockFeaturesArray1 = {"user_id","event_id"};
ArrayList<String> mockFeaturesList1 = new ArrayList<String> (Arrays.asList(mockFeaturesArray1));
when(mockObj.describeTable(tableName, parentDirectoryPath)).thenReturn(mockFeaturesList1);
然后我有了我的 Test 方法,它随后从内部调用 describeTable
方法。我检查了调用describeTable
时的参数:tableName
和parentDirectoryPath
与我在 initalize 方法中定义的参数相同。
但是,我仍然得到一个空返回值。我不明白这种行为。也许我没有正确使用Mockito?
编辑
我的测试方法是这样的:
@Test
public void testComplexFeaturesExistingRun() {
String[] args = {masterConfigPath, runFilesPath, rootDir};
DriverClass driver = new DriverClass();
driver.main(args);
}
所以driver.main调用了describeTable方法,我试图模拟它的行为。
编辑 2
我的描述蜂巢表类是:
public class DescribeHiveTable {
public ArrayList<String> describeTable(String tableName, String parentDirectoryPath){
String hiveQuery = "'describe " + tableName + "';";
String bashScriptFile = parentDirectoryPath + "/describeTable.sh";
.
.
.
final Process process = builder.start();
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
while((line=br.readLine())!=null) {
String[] output = line.split("t");
columnList.add(output[0]);
}
return columnList;
这就是我调用描述表的方式:
DescribeHiveTable describeTable;
describeTable = new DescribeHiveTable();
ArrayList<String> columnList = describeTable.describeTable(tableName, runFile.getParent());
使用 Mockito 的方法是
private DescribeHiveTable mockObj; // must be accessible to Test methods
@Before
public void initialize(){
this.mockObj = Mockito.mock(DescribeHiveTable.class);
<etc>
}
@Test
public void testComplexFeaturesExistingRun() {
/* test the objects that are set up to use this.mockObj,
and not the usual type of DescribeHiveTable */
}
请注意,
describeTable = new DescribeHiveTable();
意味着您使用的是新的、未模拟的DescribeHiveTable
,而不是模拟的mockObj
。
但看起来您无法控制DriverClass
使用的DescribeHiveTable
实例? 如果是这种情况,那么要么
- Mockito不会帮助你 - 或者你至少也必须嘲笑
DriverClass
;或者 - 您必须使用反射将
DriverClass
中的describeTable
替换为mockObj
。
DescribeHiveTable
初始化DriverClass
(前提是DescribeHiveTable
是 DriverClass
的实例变量),如下所示:
public class TestClass{
@Mock
DescribeHiveTable mockObj;
// This will create a new instance of DriverClass with a mock of DescribeHiveTable
@InjectMocks
DriverClass driver;
@Before
public void init() {
MockitoAnnotations.initMocks(this);
tableName = "clslog_assessments";
parentDirectoryPath = "src/test/resources/TEST18/RunFiles";
mockFeaturesArray1 = new String[] { "user_id", "event_id" };
mockFeaturesList1 = new ArrayList<String>(
Arrays.asList(mockFeaturesArray1));
when(mockObj.describeTable(tableName, parentDirectoryPath)).thenReturn(
mockFeaturesList1);
}
@Test
public void test() {
// when(methodCall)
assertEquals(mockFeaturesList1, driver.main());
}
}