我正在创建处理器来收集数据并在列表中提供它们。但当我试图为我的方法创建测试时,我发现了断言错误。我做错了什么?
我的班级:
@AllArgsConstructor
public class ZteProcessor implements OurProcessor {
private final static String VENDOR = "ZTE";
private String jsonString;
private Map<String, String> metricsGU;
private Map<String, String> metricsUMTS;
private Map<String, String> metricsLTE;
@Override
public List<TimingAdvance> getTA() throws ParseException, NotFoundPatternOrMetricsException {
TimeAdvanceDataStore data = new TimeAdvanceDataStore();
AllDataFromJSONFile fromJSONFile = ProcessorUtil.getAllData(jsonString);
if (jsonString.contains("String")) {
return data.allDataToTimingAdvance(VENDOR, fromJSONFile, metricsGU, 2);
} else if (jsonString.contains("String-2")) {
return data.allDataToTimingAdvance(VENDOR, fromJSONFile, metricsUMTS, 3);
} else if (jsonString.contains("String3")) {
return data.allDataToTimingAdvance(VENDOR, fromJSONFile, metricsLTE, 4);
} else {
throw new NotFoundPatternOrMetricsException();
}
}
}
我的测试:
@RunWith(PowerMockRunner.class)
@PrepareForTest({ProcessorUtil.class})
public class ZteProcessorTest {
@Mock
private AllDataFromJSONFile fromJSONFile;
@Mock
private TimeAdvanceDataStore data;
private OurProcessor processor;
private TimingAdvance timingAdvance = new TimingAdvance();
private Map<String, String> metricsGU = new HashMap<>();
private Map<String, String> metricsUMTS = new HashMap<>();
private Map<String, String> metricsLTE = new HashMap<>();
@Test
public void getTATest() throws Exception {
String jsonString = " { String : value}";
processor = new ZteProcessor(jsonString, metricsGU, metricsUMTS, metricsLTE);
List<TimingAdvance> list = new ArrayList<>();
list.add(timingAdvance);
PowerMockito.mockStatic(ProcessorUtil.class);
when(ProcessorUtil.getAllData(jsonString)).thenReturn(fromJSONFile);
when(data.allDataToTimingAdvance(jsonString, fromJSONFile, metricsGU, 2)).thenReturn(list);
assertEquals(list, processor.getTA());
}
}
堆栈跟踪:
java.lang.AssertionError:
Expected :[TimingAdvance{filial='null', vendor='null', cellName='null', periodDate=null, taMetrics=null}]
Actual :[]
<Click to see difference>
at org.junit.Assert.fail(Assert.java:88)
at org.junit.Assert.failNotEquals(Assert.java:834)
at org.junit.Assert.assertEquals(Assert.java:118)
at org.junit.Assert.assertEquals(Assert.java:144)
我的ZteProcessor使用类ProcessorUtill
的静态方法getAllData(jsonString)
。为此,我使用了powermock。
问题源于这样一个事实,即您在TimeAdvanceDataStore data
mock上设置了期望值,但在测试中的方法中创建了TimeAdvanceDataStore
的新实例。
由于您已经在使用PowerMockito,您可以使用新的对象创建,如
PowerMockito.whenNew(TimeAdvanceDataStore.class)
.withAnyArguments().thenReturn(data);
最重要的是,想想你的应用程序中有多少ZTEP处理器和TimeAdvanceDataStore。您是否总是希望在每次对getTA的调用中都有一个TimeAdvanceDataStore的新实例?
如果没有,只需在构造函数中传递TimeAdvanceDataStore。
如果是,当PowerMockito不在您的支配范围内时,常见的方法是:
- 将TimeAdvanceDataStore的工厂传递给ZTEProcessor构造函数
- 将TimeAdvanceDataStore传递给getTA方法
- 提取构造TimeAdvanceDataStore的方法并在测试中重写它