2

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

4
  • Might be a typo but that's an invalid declaration statement. Probably missing the type of the variable. Commented Apr 15, 2014 at 14:24
  • 1
    Do you need it to be static or did you only make it static to facilitate testing? If you don't need it to be static for reasons other than testing then making it static is almost certainly the wrong thing to do. It's usually best to pass in dependencies through your constructor. Commented Apr 15, 2014 at 14:26
  • well its only for testing and that is what seems suspicious to me Commented Apr 15, 2014 at 14:30
  • 1
    Have you considered using a dependency injection? Commented Apr 15, 2014 at 14:30

1 Answer 1

1

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...
}
Sign up to request clarification or add additional context in comments.

1 Comment

thats what I am already doing, my question is not how to mock it but whether is it okay to use static variable just for testing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.