简体   繁体   English

如何使用 Spock 模拟重载的 Java 方法

[英]How to mock an overloaded Java method using Spock

I have a Java class MyClass with an overloaded method process:我有一个带有重载方法进程的 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;
    }
}

I want to test the first process() method using Spock.我想使用 Spock 测试第一个 process() 方法。 I am trying to use a Spy to mock the overloaded process(ProcessClass).我正在尝试使用 Spy 来模拟重载的进程(ProcessClass)。 Here's testProcess.groovy so far:到目前为止,这是 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

This method does not work to mock the method process(ProcessClass...) as I would have expected.这种方法不能像我预期的那样模拟方法 process(ProcessClass...)。 I have consulted http://spockframework.org/spock/docs/1.0/interaction_based_testing.html but I cannot figure it out.我已经咨询过http://spockframework.org/spock/docs/1.0/interaction_based_testing.html但我无法弄清楚。

How can I mock MyClass.process(ProcessClass) so that I can return a fake answer from it and pass it to the other process function?我如何模拟 MyClass.process(ProcessClass) 以便我可以从中返回一个假答案并将其传递给另一个进程函数?

Spock mocks, stubs and spies are based on Java or CGLIB dynamic proxies. Spock 模拟、存根和间谍基于 Java 或 CGLIB 动态代理。 Those in turn create subclasses suring runtime, overriding all public methods and hooking into them to provide the fancy features you need for mock testing.这些反过来创建子类确保运行时,覆盖所有公共方法并挂钩到它们以提供模拟测试所需的花哨功能。 You however use private methods, which explains why this does not work.然而,您使用私有方法,这解释了为什么这不起作用。 Furthermore, it is bad practice to test private methods and to use spies unless absolutely necessary.此外,除非绝对必要,否则测试私有方法和使用间谍是不好的做法。 What makes it necessary to use a spy here?是什么让我们有必要在这里使用间谍?

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

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