Mocking is about creating a Fake Object
to represent a dependency in the class Under Test
. Suppose we have a dependency relationship between two classes : ClassA
and ClassB
, as ClassA
depends on ClassB
to perform an action.
While testing ClassA
(your class Under Test
), you will have to mock ClassB
(your Fake Object
).
What mocking really allows you to do, is to set a control on how you want the methods in ClassB
to behave while your are testing ClassA
, and in general limits the dependency with real objects (database, network connection, API etc...).
An example:
class ClassA {
ClassB b;
public int doSomethingDependingOnClassB() {
return b.iAmHelpingClassA();
}
}
Your test will look something like this :
class ClassATest {
@Mock
private ClassB classBMock;
@InjectMocks
private ClassA underTest;
@Test
void testDoSomethingDependingOnClassB() {
when(classBMock.iAmHelpingClassA()).thenReturn(20);
int excepectedResult = 20;
assertEquals(excepectedResult, underTest.doSomethingDependingOnClassB());
}
}
Mocking Frameworks will provide you some methods or annotations to help you setup your test scenario.
Coming to your case, you will have to mock the HttpClient
and define what you want the call of your methods will return (here, newBuilder()
and authenticator()
).
As you said mocking can be a vast and difficult topic, but as everything, you have understand the basic principle. Your friends here are Google or Youtube. There are a lots of good tutorials that can help understand mocking in unit testing.