-1

Here is an example class.

public class Example {

    private String method1() {
        return "Hello";
    }

    private String method2() {
        //Makes an external API call which I can't make
        return "World";
    }

    public String methodBeingTested() {

        String m1 = method1();
        String m2 = method2();
        return m2
    }
}

My intention is that the unit test passes through method1() for code coverage purposes, but does NOT pass through method2() because it can't be called!

Here is what I've tried:

  1. Creating a Mock of the Example class and doing a .when(exampleMock.methodBeingTested()).thenReturn(createdString) but that doesn't end up making the call at all (Shown by code coverage)

  2. Not creating the Mock but passing an actual instance, .when(actualExampleInstance.methodBeingTested()).thenReturn(createdString) in which case the function method2() does get called and an error is thrown because I still can't actually make the call to the external API but the code needs to be there..

ababuji
  • 1,683
  • 2
  • 14
  • 39

2 Answers2

2

It's not possibile with such implementation - what you can do is to refactor the code and move method1 and method2 to some external classes, inject them and mock the second one in the test

// Such interfaces you can implement package-private due to visibility purposes
public interface Processor1 {
    String method1(); 
}

public interface Processor2 {
    String method2(); 
}

public class Example {
    private Processor1 p1;
    private Processor2 p2;

    public String methodBeingTested() {
        String m1 = p1.method1();
        String m2 = p2.method2();
        return m2
    }
}
m.antkowicz
  • 13,268
  • 18
  • 37
0

You can Mock the object which is used to make API call.

check this post how to mock a URL connection

Shanid
  • 93
  • 2
  • 8