3

我正在使用 JMockit 对调用不同 Web 服务并填充数据库的数据服务进行单元测试。我正在模拟每个 Web 服务调用,并使用期望/结果向服务提供我的返回数据。

我遇到了一个问题,我必须遍历对象列表并每次使用不同的参数调用 Web 服务。我想捕获参数,以便可以将其输入到 CreateTestData 方法中,该方法将返回我想要的。数据集有些相互依赖

测试类:

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

}
}

这可能吗?

4

1 回答 1

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);
  }
}

这将“记录”您的调用并允许您“捕获”参数。

或检查验证调用参数

我使用了类似的代码

mockedService.doMethod(with(new Object() {
  public void validate(SomeArg arg) {
    assertThat(arg.getProperty(), is(equalTo("expectation"));
  }
});
于 2012-11-06T22:26:35.940 回答