简体   繁体   English

在抽象类中使用静态变量

[英]Using static variable in abstract class

I am using a static member variable in my base abstract class and static getters/setters for it. 我在基本抽象类中使用了静态成员变量,并为其使用了静态获取器/设置器。 Here is my class structure: 这是我的课程结构:

public abstract class Parent{
     private static XmlService xmlService;
     //getters and setters for xmlService     
}

This xmlService is used in child classes for xml conversion etc. However, the instances of child classes are created at runtime based on the data using another service. 此xmlService用于子类中以进行xml转换等。但是,子类的实例是在运行时基于数据使用另一个服务创建的。 Now I want to test with junit and need to mock the xmlService. 现在,我想用junit进行测试,并需要模拟xmlService。 If I dont make it static, I do not see any way to initialize xmlService with mock. 如果不将其设置为静态,则看不到使用模拟初始化xmlService的任何方法。

So my question is that is this approach (static + abstract) is okay or does it break any OOP concepts etc. I don't see any issues with this though but just want an opinion. 因此,我的问题是这种方法(静态+抽象)是否可行,或者是否破坏了任何OOP概念等。尽管如此,我看不到任何问题,只是想发表意见。

Thanks 谢谢

EDIT: I think based on the comments, I will review my design and most likely will go with constructor injection approach 编辑:我认为根据评论,我将审查我的设计,并且很可能会采用构造函数注入方法

You have a setter for the XML service - just set a mock object there in your @Before method: 您有XML服务的设置器-只需在@Before方法中设置一个模拟对象@Before

public class ParentTest {
    private Parent parent;
    private XmlService origService;

    @Before
    public void setUp() {
       parent = new Parent() { /* anonymously implement the abstract methods */ };
       origService = parent.getXmlService();
       XmlService moxkService = Mockito.mock(XmlService.class);
       // record some behavior...

       parent.setXmlService(mockService);
    }

    @After
    public void tearDown() {
        // Restore the original service
        parent.setXmlService(origService);
    }

    // unit tests...
}

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

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