简体   繁体   English

用Java进行集成测试的模拟/存根

[英]Mock / stub with integration testing in Java

I'm using rest-assured for integration testing on my endpoints. 我正在使用可放心的端点上的集成测试。 One of the endpoints has a dependency to another resource (it calls another API conditionally). 端点之一对另一资源具有依赖性(它有条件地调用另一个API)。 Is there a way for me to stub out the API call so I can write a test for that case? 有没有一种方法可以对API调用进行存根处理,以便为该情况编写测试?

Lets say your code calls endpointB internally via http, you can stub that api by using https://github.com/katta/fakerest or https://github.com/azagniotov/stubby4j .So when your code makes a call internally to the another api, it will hit these stubs, which will return a dummy response always. 假设您的代码通过http内部调用了endpointB,则可以使用https://github.com/katta/fakeresthttps://github.com/azagniotov/stubby4j对api进行存根处理,因此当您的代码在内部进行调用时另一个API,它将点击这些存根,并将始终返回虚拟响应。 Hope this helps. 希望这可以帮助。

interface IDataProvider {
 string RetrieveData();
}

class StandardDataProvider : IDataProvider {
 public string RetrieveData(){
  // call to API
 }
}

class Program {
 private IDataProvider _dataProvider;

 public Program(IDataProvider provider = null) {
  _dataProvider = provider ?? new StandardProvider();
 }

 public void MethodToTest(){
  var data = _dataProvider.RetrieveData();
  // do your thing
 }
}

In the tests you can mock the data by creating your own IDataProvider object and working with its data. 在测试中,您可以通过创建自己的IDataProvider对象并使用其数据来模拟数据。

class TestDataProvider : IDataProvider {
 public string RetrieveData(){
  return "my own data";
 }
}

class Test {
 [TestMethod]
 public void TestProgram(){
  var obj = new Program(new TestDataProvider);
  var result = obj.MethodToTest();
  // asserts
 }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM