Skip to content

Instantly share code, notes, and snippets.

@daddykotex
Last active April 20, 2017 10:51
Show Gist options
  • Save daddykotex/6342e92a201f5472f226 to your computer and use it in GitHub Desktop.
Save daddykotex/6342e92a201f5472f226 to your computer and use it in GitHub Desktop.
Mock Android TextUtils static method
import android.text.TextUtils;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import static junit.framework.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
import static org.mockito.Matchers.any;
import static org.powermock.api.mockito.PowerMockito.mockStatic;
import static org.powermock.api.mockito.PowerMockito.when;
@RunWith(PowerMockRunner.class)
@PrepareForTest(TextUtils.class)
public class DummyAndroidTextUtilsMockTest {
private class DummyClass {
String a;
String b;
private DummyClass(String a, String b) {
this.a = a;
this.b = b;
}
public boolean bothEquals() {
return TextUtils.equals(a, b);
}
}
@Before
public void setUp() throws Exception {
mockStatic(TextUtils.class);
when(TextUtils.equals(any(CharSequence.class), any(CharSequence.class))).thenAnswer(new Answer<Object>() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
CharSequence a = (CharSequence) invocation.getArguments()[0];
CharSequence b = (CharSequence) invocation.getArguments()[1];
if (a == b) return true;
int length;
if (a != null && b != null && (length = a.length()) == b.length()) {
if (a instanceof String && b instanceof String) {
return a.equals(b);
} else {
for (int i = 0; i < length; i++) {
if (a.charAt(i) != b.charAt(i)) return false;
}
return true;
}
}
return false;
}
});
}
@Test
public void testCase() throws Exception {
assertTrue(new DummyClass("test", "test").bothEquals());
assertFalse(new DummyClass("test", "false").bothEquals());
}
}
@pulkitkumar
Copy link

Getting a java.lang.NoClassDefFoundError: org/mockito/cglib/proxy/Enhancer when running this.
What wrong could I be doing?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment