【问题标题】:Intercepting method calls in Java with mockito or proxies使用 mockito 或代理拦截 Java 中的方法调用
【发布时间】:2018-06-14 08:53:59
【问题描述】:

我想知道是否有一种方法可以拦截与服务器联系并返回我的应用程序的配置设置然后为我的测试返回所需值的类方法调用。我的应用是这样的

package application;

class Application { 
  private static synchronized void getServerConfiguration() {
      ConfigurationAccessor accessor = new ConfigurationAccessor();
      optionOne = accessor.getOption("option-one"); // <- intercept this method call and return different value
      ...
  }
}

在我的测试中,我需要使用应用程序的运行实例来运行 GUI 测试:

package tests;

class SomeTest {

@BeforeClass public static void startApplication() {
  createUsers();
  Application.start(); <- this will start application and load config from server
}

很遗憾,无法通过代理服务器运行连接来模拟响应。

【问题讨论】:

  • 您可以使用 PowerMockito 来实现。 This question 应该是正确的方向。

标签: java testing junit


【解决方案1】:

如果您将 ConfigurationAccessor 注入到 Application 类中,您将能够在 SomeTest 中注入模拟。 IE。创建一个构造函数

Application(ConfigurationAccessor accessor) {
    this.accessor = accessor;
}

那么在你的测试中你就可以

Application target;
@Mock
ConfigurationAccessor accessorMock;
@Before
public void setUp() {
    target = new Application(accessorMock);
}

【讨论】:

  • 不幸的是,我无法更改 Application 类。这是一大堆遗留代码,我不知道它仍然如何工作
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-04
  • 2014-10-11
相关资源
最近更新 更多