I'm attempting to test the isKeyguardSecure()
method of the KeyguardManager class in an Android application.
I've tried and failed using EasyMock , Mockito , and PowerMock to create a mock KeyguardManager
object. Below are my attempts and the error messages received.
EasyMock
KeyguardManager keyguardManagerMock = EasyMock.createMock(KeyguardManager.class);
Error message: java.lang.IllegalArgumentException: android.app.KeyguardManager is not an interface
Mockito and PowerMock
KeyguardManager mockedKeyguardManager = Mockito.mock(KeyguardManager.class);
KeyguardManager mockedKeyguardManager = PowerMockito.mock(KeyguardManager.class);
Error messages: java.lang.VerifyError: mockit/internal/startup/Startup
java.lang.VerifyError: org/mockito/cglib/core/ReflectUtils
One explanation for this states that the root problem is with the Dalvik virtual machine that Android devices run. Can anyone verify this? Is it possible to mock the KeyguardManager
class using any available mocking library that will work in testing an Android app?
Thanks!
Your EasyMock version is too old. PowerMock isn't required for that. Using EasyMock 3.4, I did the following and it worked perfectly:
public static void main(String[] args) {
KeyguardManager manager = createMock(KeyguardManager.class);
expect(manager.isKeyguardSecure()).andReturn(true);
replay(manager);
assertTrue(manager.isKeyguardSecure());
verify(manager);
}
Use PowerMock with EasyMock.
Dependencies:
testCompile 'junit:junit:4.12'
testCompile 'org.easymock:easymock:3.3.1'
testCompile 'org.powermock:powermock-core:1.6.2'
testCompile 'org.powermock:powermock-api-easymock:1.6.2'
testCompile 'org.powermock:powermock-module-junit4:1.6.2'
Sample code:
package com.example.user.exampleapp;
import android.app.KeyguardManager;
import org.easymock.EasyMock;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.easymock.PowerMock;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
@RunWith(PowerMockRunner.class)
@PrepareForTest(KeyguardManager.class)
public class KeyguardTest {
@Test
public void testKeyguard() {
KeyguardManager keyguardMock = PowerMock.createMock(KeyguardManager.class);
EasyMock.expect(keyguardMock.isKeyguardSecure()).andReturn(false);
PowerMock.replayAll();
System.out.println("is locked " + keyguardMock.isKeyguardSecure());
PowerMock.verifyAll();
}
}
Output:
is locked false
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.