Search code examples
unit-testinggroovymockingmop

Unit tests in Groovy for Java code - how to mock java classes?


I'm introducing Groovy in a large project written in Java, starting (as most of guys do) with writing unit test in Groovy for Java classes.

So the problem I have is:

Imagine I have 2 Java classes, ClassA and ClassB, interacting this way:

public class ClassA {
  public void doSomething(...) {

    ...//something

    ClassB.invokeSomeStaticMethod((someParam);

    ...//something

  }
}

ClassB is service looking up some data from database. I'm testing ClassA functionality. So I would like to mock ClassB somehow, so it's invokeSomeStaticMethod() in the context of my unit test would return mocked value for testing. As far as I understand the main problem here is that both classes are Java and hence ClassB.invoke... method is not routed thru Groovy MOP, which the Groovy Mocks are based on. Am I right? And how could I achieve what I need?

Thanks! Mikhail


Solution

  • AFAIK, Groovy MOP won't be able to replace the call to ClassB.invokeSomeStaticMethod(someParam). You can use a framework like JMockit to help you mock the static method.