Reputation: 177
Below is the code to be mocked:
private MultivaluedMap<String, Object> addAuthorizationAndCorrelationIdHeader(MultivaluedMap<String, Object> httpHeaders) {
if(httpHeaders == null)
httpHeaders = new MultivaluedHashMap<>();
String token = new JSONWebToken().getUserInfo().getToken("SYSTEM", "JobScheduler");
}
How to mock new JSONWebToken() part?
Upvotes: 1
Views: 23995
Reputation: 140427
There are two options:
new
new
calls in your production code. Instead, you use dependency injection; for example by using a factory (as in the answer you already got), or by passing in such objects via constructors.Long story short: using new
can lead to "hard to test" code. The real answer is to learn how to create testable code; a good starting point are these videos.
Upvotes: 0
Reputation: 5871
You can use spy org.mockito.Mockito.spy
. it will look something like this..
@RunWith(MockitoJUnitRunner.class)
class YourTestClass {
@Test
public void yourTestCase() {
JSONWebToken jwt = spy(new JSONWebToken());
UserInfo mockUserInfo = mock(UserInfo.class);
when(jwt.getUserInfo()).thenReturn(mockUserInfo);
}
}
Upvotes: -1
Reputation: 1533
You should create some kind of JSONTokenFactory like:
public class JSONWebTokenFactory {
public JSONWebToken creaateWebToken() {
return new JSONWebToken();
}
}
Then pass the instance of the factory to the class your're testing. Now you can pass a mock of JSONTokenFactory in tests.
Upvotes: 2