0

我需要模拟私有方法并且应该返回 true。在 ServiceImpl-execute() 中,我的请求将转到 else { },它会调用“eventRequest()”。它是一个私有的布尔 eventRequest(),所以每当 evenRequest() 调用我应该返回 true。谁能帮帮我

ServiceImplTest.java

@RunWith(PowerMockRunner.class)
@PrepareForTest({ServiceImpl.class})
public class ServiceImplTest {

    @Test
    public void testExecute() {
        Response response = serviceImpl.execute(request);
        Assert.assertNotNull(pushResponse);
        Assert.assertEquals(true, pushResponse.isIsSuccess());
    }
}

ServiceImpl.java

public class ServiceImpl {
    public Response execute(Request request) {
        Response response = null;
                boolean isSuccess;
                if (returnMockResponse(request, notifyRqst)) {
                    isSuccess = true;
                } else {
                    isSuccess = eventRequest(notifyXmlRqst);
                }
        response = ResponseBuilder.createResponse(isSuccess);
        return response;
    }

    // Need to mock below private method and should return true.
    private boolean eventRequest(String request) throws Exception {
        return eventNotifyResponse.isIsSuccess();
    }
}

ResponseBuilder.java

public class ResponseBuilder {
    public Response createResponse(boolean result) {
            Response response = new Response();
            response.setIsSuccess(result);
            return response;
    }    
}
4

3 回答 3

2

您可以正常创建 eventNotifyResponse 的模拟,然后使用 Whitebox 设置私有(内部)字段。

假设您的字段 eventNotifyResponse 是名为 EventNotifyResponse 的类型,则测试类将类似于:

    EventNotifyResponse evtNotifyResponseMock = mock(EventNotifyResponse.class);
    when(evtNotifyResponseMock.isIsSuccess()).thenReturn(true);
    Whitebox.setInternalState(serviceImpl, "eventNotifyResponse", evtNotifyResponseMock);

Whitebox 是 Powermock 的一个类 (org.powermock.reflect.Whitebox)。
setInternalState 已重载。在示例中,使用的参数是:

  1. 要注入的目标对象(您正在测试的对象)
  2. 要设置的内部字段的名称(字符串)
  3. 值本身,在这种情况下是一个模拟
于 2015-07-09T14:17:19.977 回答
0

默认情况下,在 jUnit 或 jMock 中这是不可能的,您可以将私有更改为公共,也可以调用内部调用私有方法的公共方法,并确保输入导致私有方法被调用和覆盖。

于 2015-07-09T13:54:14.717 回答
0

Have you try with PowerMock.createPartialMock(ClassWithPrivateMethod.class, "nameOfTheMethodToMock") and PowerMock.expectPrivate(mockObject, "nameOfTheMethodToMock", argument1, argument2) as describe in the wiki off powermock ?

https://code.google.com/p/powermock/wiki/MockPrivate

or perhaps see the answer of this question ...

How to mock private method for testing using PowerMock?

于 2015-07-09T14:13:05.627 回答