【问题标题】:How to write test class with @Autowired variable for inherited class如何使用@Autowired 变量为继承的类编写测试类
【发布时间】:2016-12-28 14:30:20
【问题描述】:

我在使用 SPOCK 编写测试用例时遇到问题。谁能帮帮我?

我有如下类和接口,

    //Helper class

    public class ObjClass{

        //Defining all property variables & corresponding getters & setters methods.

    }


    //Interface

    public interface B{ 

        //Declaring custom methods for Mongo repository.

        public int getId();
    }

    public interface A extends MongoRepository<ObjClass, Serializable>, B{ 

    //Defining some standard MongoRepository methods here

    }

    // Implementation Classes
    public class Aimpl implements B{ 

        //implementing all B interface methods

    }

    public class ctrlClass{

        @Autowired
        A aObj;

       public int getIdValue(){
         return aObj.getId();
       }

    }

以下是对应的SPOCK测试用例:

class test extends Specification
{
    ctrlClass obj1
    A obj2   //interface class object


    def setup(){
        obj1 = new ctrlClass();

        obj2 = new Aimpl(); //Creating object for interface using impl class.

       obj1.aObj = obj2

    }

def "test"(){
    when:
    def a = obj2.getIdValue()
    then:
    //validating some conditions here with 'a' value
}

}

执行上述测试用例时出现以下错误,

无法将对象 Aimpl 转换为 A 类。

上述相同的场景在 Spring @Autowired 上运行良好。但不是在斯波克。

*

SPOCK 中的@Autowired 是否有任何替代方案可用?请向我推荐一些解决方案和您的 cmets。

*

【问题讨论】:

    标签: spring groovy spring-boot junit spock


    【解决方案1】:

    您遇到的问题是 Spring 将接口与相关实现绑定的能力。

    如果您的接口只有一个实现,并且单个实现具有注释@Component 并启用了Spring 的component scan,那么Spring 框架可以成功推断出接口与其实现之间的关系。

    如果没有启用组件扫描,那么应该在你的spring配置文件中显式定义bean(例如application-config.xml)。

    Aimpl 和 A 的转换不能成功,因为继承类/接口不同。

    您应该像下面这样更改代码:

    public class ctrlClass{
    
       @Autowired
       Aimpl aObj;
    
      public int getIdValue(){
        return aObj.getId();
      }
    }
    

    并在测试类中进行以下更改:

    A obj2   //interface class object
    

    应改为:

    Aimpl obj2   
    

    【讨论】:

    • 这样改的话public class ctrlClass{ @Autowired Aimpl aObj; public int getIdValue(){ return aObj.getId(); } }就不能使用接口A的方法了吧?注意:但在我目前的继承结构中,我可以同时使用 A 和 B 的接口方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-23
    • 1970-01-01
    • 2023-02-09
    • 2015-11-05
    相关资源
    最近更新 更多