简体   繁体   中英

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?

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.

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);
}
}

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM