Shubham Kumar
Shubham Kumar

Reputation: 177

How to mock a new Object Creation in Java

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

Answers (3)

GhostCat
GhostCat

Reputation: 140427

There are two options:

  1. You use mocking frameworks such as PowerMock or Mockito that allow for mocking calls to new
  2. You avoid doing 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

J-J
J-J

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

g-t
g-t

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

Related Questions