Pergunta

Possible Duplicate:
jmock mocking a static method

I am working on a legacy unit test which uses static methods of a class XX. I have now changed the class to get a field value from Spring application context. The unit test now fail as the class XX cannot be initialized.

I cannot wrap the class XX with a dummysupport class since the logic to be tested is complex and the call to class XX is nested within multiple layers of calls to other legacy classes. So i am trying to find a way to mock the static methods within the class class XX. Is there a way do this? I am using Jmock library.

Foi útil?

Solução

There does not appear to be a way to mock static methods in JMock. See this related thread. The creators of JMock appear to take the elitist view that if you have static methods in your code, your code is unworthy to be tested using JMock.

I would suggest using a tool like JMockit that provides a more full-featured mocking toolset.

Outras dicas

I belive powermock allows you to mock statics as detailed here

I have also had this problem in the past and have managed to code around it so I can use JMock by making the method non static but having a static reference to the class.

For example

public ClassToMock {
    public static final ClassToMock INSTANCE = new ClassToMock();

    private ClasstToMock() {};

    public void newNonStaticMethod1(){}
}

instead of

public ClassToMock {

    public ClasstToMock() {};

    public void static origStaticMethod1(){}
}

Now your method call would be

ClassToMock.INSTANCE.newNonStaticMethod1();

as newNonStaticMethod1() is notn static you can now mock this.

As the CalssToMock ctor is private it can only be accessed through the static instance.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top