ainlolcat
ainlolcat

Reputation: 554

Mock class with missing dependencies

I have third party component which I want to mock but it returns class which have complex hierarchy and some of interfaces have static fields which initialized by some class which not available in API. I don't need anything from hidden class.

Sample: Assume we want to mock class MutableCombo which implements Combo. But interface Combo has fields initialized by Breaker. Breaker is part of implementation package and cannot be accessed by developer during compilation and tests.

public interface Combo{
    String FUU = Breaker.getFoo();
    String BAR = Breaker.getBar();
}
public class MutableCombo implements Combo;

I want to test my class which working with MutableCombo but cannot mock it because

java.lang.NoClassDefFoundError: Breaker
    at Combo.<clinit>(Combo.java:36)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:169)

Upvotes: 3

Views: 1198

Answers (1)

Finglas
Finglas

Reputation: 15709

You'll need an adapter here. You shouldn't be mocking types you don't own for starters. Treat MutableCombo as an implementation detail. For example:

public class ExampleMutableCombo implements IExampleMutableCombo
{
     public String DoFoo()
     {
         return Breaker.getFoo();
     }

     public String DoBar()
     {
         return Breaker.getBar();
     }
}

Make your code use IExampleMutableCombo. This interface is now yours. Use this in your production code. As you own this interface you can mock this role - you can introduce a fake combo for testing such as:

public class FakeExampleMutableCombo implements IExampleMutableCombo
{
     public String DoFoo()
     {
         return "Foo";
     }

     public String DoBar()
     {
         return "Bar";
     }
}

Now all your tests can work with the stubbed out class, while your production code can make use of the ExampleMutableCombo. The key is to "code to an interface", not a type.

Upvotes: 3

Related Questions