【问题标题】:Junit for functions depending on other applications依赖于其他应用程序的功能的 Junit
【发布时间】:2017-09-06 10:13:28
【问题描述】:

我需要为使用 maven 开发的应用程序(用 java 编写)实现 Junit。我的应用程序中的一些功能依赖于其他应用程序,当我们在 SDN 控制器中与其他应用程序一起启动它时,它获取该应用程序的服务并在我的应用程序中使用它来连接到数据库等。如何测试依赖于其他应用的功能并连接到db?

【问题讨论】:

  • 通过模拟这些调用
  • @Stultuske 给出答案(加上一个例子:))
  • 如何模拟通话?我尝试在我的应用程序中为这些应用程序添加依赖项
  • 我在教程的回答中添加了一个链接

标签: java maven junit


【解决方案1】:

如果您需要从其他服务(甚至在同一个库中)调用方法,您可以模拟这些调用,并在单元测试本身中决定响应是什么,因此您的单元测试完全专注于该单元.

您可以使用不同的模拟库,例如 Mockito 或 unitils.easyMock:

@RunWith(StveJunit4TestClassRunner.class)
public class MyServiceTest {

  @TestedObject
  private MyService service;

  @Mock
  @InjectIntiByType
  private ExternalService external;
  // this for all services used in your service

  @Test
  public void testMethod(){
    Person result = new Person("Jack", "American");
    EasyMock.expect(external.findPerson("Jack")).andReturn(result);
    EasyMockUnitils.replay();
    // this tells you, your tested service is going to call the external service
    // and passes "Jack" as param, with result as returned value

    String country = service.getPersonCountry("Jack"); // assume this returns the country 
//  of the person returned by the external service
    assertEquals(result.getCountry(), country);

  }
}

这只是一个例子,还有很多方法可以做到这一点。

编辑:这是tutorial 的链接,您可以查看

【讨论】:

    猜你喜欢
    • 2019-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-18
    • 1970-01-01
    • 2020-11-02
    • 2015-09-19
    相关资源
    最近更新 更多