【问题标题】:PowerMockito whenNew returns nullPowerMockito whenNew 返回 null
【发布时间】:2017-09-14 09:37:27
【问题描述】:

在我无法重构的源类中(所以我不能使用建议here),有 = new XXX 的对象创建。我必须模拟他们的函数调用 X().call()。

为此,我使用了 powermock 的 whenNew() 函数。但是我在我正在测试的类中有 null ,在这种情况下是 LoginSuccessHandler 。这是我的 LoginSuccessHandlerTest 类:

@RunWith(PowerMockRunner.class)
public class LoginSuccessHandlerTest {

    @InjectMocks private LoginSuccessHandler loginSuccessHandler;
    @Mock private GuiSessionDAO guiSessionDAO;
    @Mock private UserAuthorityDAO userAuthorityDAO;
    @Mock private OrcaAuthorizationServiceBean orcaAuthorizationServiceBean;
    @Mock private OrcaAuthorizationServiceBeanService orcaAuthorizationServiceBeanService;
    @Mock private GetUserRolesReturnModel userRolesReturnModel;

    private Authentication authentication;
    private MockHttpServletRequest request;
    private MockHttpServletResponse response;

    @Before
    public void setUp() {
        request = new MockHttpServletRequest();
        response = new MockHttpServletResponse();
        authentication = new TestingAuthenticationToken("foo", "foo", "foo");
    }

    @PrepareForTest({LoginSuccessHandler.class})
    @Test
    public void onAuthenticationSuccess() throws Exception {



        whenNew(OrcaAuthorizationServiceBeanService.class).withArguments(URL.class).thenReturn(orcaAuthorizationServiceBeanService);

        p("Mocking Orca WS calls");
        when(orcaAuthorizationServiceBeanService.getOrcaAuthorizationServiceBeanPort()).thenReturn(orcaAuthorizationServiceBean);
        when(orcaAuthorizationServiceBean.getUserRoles(any(Header.class), anyString())).thenReturn(userRolesReturnModel);
        when(userRolesReturnModel.getUserRoles()).thenReturn(Collections.singletonList("ADMIN"));

        p("Starting mock log in");
        loginSuccessHandler.onAuthenticationSuccess(request, response, authentication);

        assertEquals(MockHttpServletResponse.SC_OK, response.getStatus());
    }

    private void p(String s) {
        System.out.println(s);
    }

在这里我得到 null

OrcaAuthorizationServiceBeanService service = new OrcaAuthorizationServiceBeanService(new URL(url));

当我调试时,我可以确认 powermockito 正在运行以模拟此对象创建并且正在调用此方法:

public static synchronized NewInvocationControl<?> putNewInstanceControl(Class<?> type, NewInvocationControl<?> control) {
        return newSubstitutions.put(type, control);
    }

这些是参数:

type = {Class@1755} "class com.ttech.timsgui.ldap.OrcaAuthorizationServiceBeanService"
 cachedConstructor = null
 newInstanceCallerCache = null
 name = "com.ttech.timsgui.ldap.OrcaAuthorizationServiceBeanService"
 classLoader = {MockClassLoader@2118} 
 reflectionData = {SoftReference@2119} 
 classRedefinedCount = 0
 genericInfo = null
 enumConstants = null
 enumConstantDirectory = null
 annotationData = null
 annotationType = null
 classValueMap = null
control = {MockitoNewInvocationControl@2093} 
 substitute = {InvocationSubstitute$$EnhancerByMockitoWithCGLIB$$4d9f6379@2109} "invocationSubstitute"
  CGLIB$BOUND = true
  CGLIB$CALLBACK_0 = {PowerMockMethodInterceptorFilter@2115} 
  CGLIB$CALLBACK_1 = {SerializableNoOp@2116} 

这是命中 getter 时的结果:

public static synchronized NewInvocationControl<?> getNewInstanceControl(Class<?> type) {
    return newSubstitutions.get(type);
}

type = {Class@277} "class java.net.URL"
newSubstitutions = {HashMap@1823}  size = 1
 0 = {HashMap$Node@2195} "class com.ttech.timsgui.ldap.OrcaAuthorizationServiceBeanService" -> 
  key = {Class@1755} "class com.ttech.timsgui.ldap.OrcaAuthorizationServiceBeanService"
  value = {MockitoNewInvocationControl@2137} 

this 返回 null 并且对象创建也返回 null。是什么导致了这个问题?

【问题讨论】:

  • 您应该更改您的生产代码,以便注入OrcaAuthorizationServiceBeanService 的实例。然后你可以用普通的 Mockito 来模拟它。
  • 正如我在第一句话中所说的,我无法更改生产代码并使用普通的 mockito。这就是我使用 powermockito 的原因
  • 让你用MockitoAnnotations.initMocks(this);初始化模拟
  • 我同意 pvpkiran - 查看您显示的代码,您错过了 PowerMockRunner 可能不会初始化 Mockito @Mock 带注释的模拟的事实。
  • 我现在添加并重试,仍然返回null。看起来它找不到正在调用 whenNew(OrcaAuthorizationServiceBeanService.class).withArguments(URL.class) 的带有新 URL(url) 的构造函数

标签: java junit mockito powermockito


【解决方案1】:

试试,

whenNew(OrcaAuthorizationServiceBeanService.class).withAnyArguments().thenReturn(orcaAuthorizationServiceBeanService);

【讨论】:

  • 这没有提供问题的答案。要批评或要求作者澄清,请在他们的帖子下方留下评论。 - From Review
  • 这个问题可以通过使用'withAnyArguments'而不是使用'withArguments'来解决
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多