简体   繁体   中英

Capture arguments of a static method call in Mockito

I am trying to unit test a method call in android studio using Mockito. It is something like this:

public static class DeviceMessageHandler extends Handler {
    public DeviceMessageHandler(Looper looper) {
        super(looper);
}

@Override
    public void handleMessage(Message msg) {

        try {
            switch (msg.what) {
                default:
                    String message = (String) msg.obj;

                    DeviceRequest deviceRequest = new Gson().fromJson(message, DeviceRequest.class);
                    String requestType = deviceRequest.getKey();
                    if (DeviceMessage.SOME_ACTION.equals(requestType)) {
                        sendResponseWithMessage(execId, COMMAND_STATE, "Not accepted");
                    }
                }
            }
        }
}

public static void sendResponseWithMessage(String execId, String commandState, String reasonIfAny) {
//  do some work
} catch (Exception e) {
        e.printStackTrace();
    }
}

So here I am able to call sendResponsewithMessage. I want to check the parameters being passed when I am calling this method. The problem being that it is a static method and I do not know how to capture parameters passed to a static method. I tried using PowerMock but since this is an android project, I am not able to use PowerMock. Any way I can assert the parameters passed on the method call with expected values?

This worked for me, for running PowerMock in android:

testImplementation 'org.mockito:mockito-core:3.7.7'
androidTestImplementation 'org.mockito:mockito-android:2.7.22'
testImplementation 'org.powermock:powermock-module-junit4:2.0.9'
testImplementation group: 'org.mockito', name: 'mockito-all', version: '2.0.2-beta'
testImplementation group: 'org.mockito', name: 'mockito-core', version: '3.9.0'
testImplementation group: 'org.powermock', name: 'powermock-api-mockito2', version: '2.0.9'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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