[英]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: 有两种选择:
new
new
模拟调用 new
calls in your production code. new
调用。 Instead, you use dependency injection; 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.