Reputation: 386
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
Upvotes: 2
Views: 302
Reputation: 311063
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...
}
Upvotes: 1