Jmock - How to mock a static method

Possible duplicate:
jmock mocks the static method

I am working on a unit test legacy that uses static methods of class XX. Now I have changed the class to get the field value from the context of the Spring application. unit test no longer runs because class XX cannot be initialized.

I cannot wrap class XX with dummysupport, because the logic to be tested is complex, and the call to class XX is nested in several levels of calls to other heritage classes. So I'm trying to find a way to mock static methods in a class of class XX. Is there any way to do this? I am using the Jmock library.

+4
source share
2 answers

There seems to be no way to mock static methods in JMock. See this related thread . The creators of JMock seem to consider the elitist view that if you have static methods in your code, your code is not worthy of testing with JMock.

I would suggest using a tool like JMockit , which provides a more fully functional software toolkit.

+4
source

I believe powermock allows you to make fun of statistics as detailed here

I also had this problem in the past, and I was able to create code around it, so I can use JMock, making the method not static, but having a static class reference.

for instance

public ClassToMock { public static final ClassToMock INSTANCE = new ClassToMock(); private ClasstToMock() {}; public void newNonStaticMethod1(){} } 

instead

 public ClassToMock { public ClasstToMock() {}; public void static origStaticMethod1(){} } 

Now your method call will be

 ClassToMock.INSTANCE.newNonStaticMethod1(); 

since newNonStaticMethod1 () is not static, you can now mock it.

Since CalssToMock ctor is private, access to it is possible only through a static instance.

+1
source

Source: https://habr.com/ru/post/1432774/


All Articles