简体   繁体   English

如何在Java中模拟新的对象创建

[英]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? 如何模拟新的JSONWebToken()部分?

You should create some kind of JSONTokenFactory like: 您应该创建某种JSONTokenFactory,例如:

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. 现在,您可以在测试中传递JSONTokenFactory的模拟。

You can use spy org.mockito.Mockito.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 您使用诸如PowerMock或Mockito之类的模拟框架,该框架允许对new模拟调用
  2. You avoid doing new calls in your production code. 避免在生产代码中进行new调用。 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. 长话短说:使用new可能导致“难以测试”的代码。 The real answer is to learn how to create testable code; 真正的答案是学习如何创建可测试的代码。 a good starting point are these videos . 这些视频是一个很好的起点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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