【问题标题】:How to mock an overloaded Java method using Spock如何使用 Spock 模拟重载的 Java 方法
【发布时间】:2017-06-29 10:02:36
【问题描述】:

我有一个带有重载方法进程的 Java 类 MyClass:

class MyClass {
    private String process(String requestId, String request) {
       // Initial processing, creates processObject from request
       // then class actual processing:
       String temp = process ( processObject );
       // do stuff I want to test, generate response
       return response;
    };
    private String process( ProcessClass processObject ) {
       String result;
       // do actual processing of processObject
       return result;
    }
}

我想使用 Spock 测试第一个 process() 方法。我正在尝试使用 Spy 来模拟重载的进程(ProcessClass)。到目前为止,这是 testProcess.groovy:

class TestProcessUsingString extends Specification {
   given:
      def testInput = "TestInput"
      def myObject = Spy(MyClass) {
         process(_ as ProcessClass) >> "My result string"
      }
   when:
      def response = myObject.process("TestInput")
      // Check response

此方法无法像我预期的那样模拟方法 process(ProcessClass...)。我已经咨询了http://spockframework.org/spock/docs/1.0/interaction_based_testing.html,但我无法弄清楚。

如何模拟 MyClass.process(ProcessClass) 以便从中返回虚假答案并将其传递给其他流程函数?

【问题讨论】:

  • 为什么不把要测试的东西移到可测试的方法中呢?

标签: java unit-testing groovy spock


【解决方案1】:

Spock 模拟、存根和间谍基于 Java 或 CGLIB 动态代理。反过来,它们创建子类以确保运行时,覆盖所有 public 方法并连接到它们以提供模拟测试所需的精美功能。但是,您使用私有方法,这解释了为什么这不起作用。此外,除非绝对必要,否则测试私有方法和使用间谍是不好的做法。为什么需要在这里使用间谍?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-23
    • 1970-01-01
    • 2018-01-09
    • 2022-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多