java - PowerMockito whenNew 返回 null

标签 java junit mockito powermockito

在我无法重构的源类中(因此我无法使用建议 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} 

这会返回 null,并且对象创建也会返回 null。是什么原因导致这个问题?

最佳答案

尝试,

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

关于java - PowerMockito whenNew 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46215582/

相关文章:

java - 将空值 JTextFormatted 插入双列到 mysql

java - boolean 类型序列化和反序列化单元测试失败

java - 为接口(interface)或每个实现编写单元测试?

mockito - 在基于 spock 的测试中对 mockito 模拟对象进行 stub

java - Junit 测试调用rest api的方法

java - 如何将数据库表中的空字段映射为 double ?

java - 在 C++ 中获取 java.home 的位置

KVM 上的 Java 意外停止世界

java - 试图从类 javax.crypto.Cipher JUNIT 访问类 javax.crypto.JceSecurity

java - 无法使用 PowerMock 模拟 httpClient.execute 方法