简体   繁体   中英

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. Now I want to test with junit and need to mock the xmlService. If I dont make it static, I do not see any way to initialize xmlService with mock.

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.

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:

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...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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