我正在使用JMockit进行单元测试,这是一种调用不同Web服务并填充数据库的数据服务。我正在模拟每个Web服务调用,并使用Expectations / results为我的返回数据提供服务。
我遇到了一个问题,我必须迭代一个对象列表并每次使用不同的参数调用Web服务。我想捕获参数,以便我可以将它提供给CreateTestData方法,该方法将返回我想要的内容。 dataSets在某种程度上依赖于彼此
测试类:
public class testDataService {
@Mocked
private WebService1 webServiceClientMocked1;
@Mocked
private WebService2 webServiceClientMocked2;
@Autowired
private DataService dataService;
@Test
public void createTestData() {
final DataSet1 dataSet1 = CreateMyTestData.createDataSet1();
final DataSet1 dataSet2 = CreateMyTestData.createDataSet2();
// these are populated using other methods not shown
final List<String> listStrings = new ArrayList<String>();
final List<String> entities = new ArrayList<String>();
new Expectations() {{
webServiceClientMocked1.getDataSet1("stringA", true);
result = dataSet1;
}};
new Expectations() {{
webServiceClientMocked2.getDataSet2("stringB");
result = dataSet2;
}};
new Expectations() {{
for(String s : listStrings){
webServiceClientMocked1.getDataSet4(s,(List<String>) any);
returns(CreateMyTestData.createDataSet4(s, entities));
}
}};
//doesnt work
//new Expectations() {{
//webServiceClientMocked1.findDataPerParamters(anyString, (List<String>) any );
//result = CreateMyTestData.createDataSet4(capturedString, capturedListStrings);
//}};
//call data service to test
dataService.doSaveData();
}
数据服务类:
public class DataServiceImpl implements DataService
{
public void doSaveData() {
//do a bunch of stuff
dataSet1 =webServiceClientMocked1.getDataSet1("stringA", true);
//do more stuff
dataSet2 = webServiceClientMocked2.getDataSet2("stringB");
Collection<Stuff> dataSet3 = saveToDB(dataSet2); //save data and return a different set of data
for(Stuff data : dataSet3) {
//take dataSet3, iterate over it and call another webservice
dataSet4 = webServiceClientMocked1.getDataSet4(data.getStringX(), data.getListStrings());
// keep doing more junk
}
}
这可能吗?
答案 0 :(得分:2)
你可以使用类似的东西:
final List<String> args = Arrays.asList("1","2","3","4");
final Map<String,Object> results = ....
然后在期望中:
new Expectations() {
{
for (arg : args) {
mockedService.invoke(arg);
returning(results.get(arg);
}
}
这将“记录”您的调用并允许您“捕获”参数。
或检查Validating invocation arguments
我使用了像
这样的代码mockedService.doMethod(with(new Object() {
public void validate(SomeArg arg) {
assertThat(arg.getProperty(), is(equalTo("expectation"));
}
});