Forked from daddykotex/DummyAndroidTextUtilsMockTest.java
Created
August 14, 2016 07:58
-
-
Save j796160836/5ceacb47de690bb1c9b5ebb6c87dff91 to your computer and use it in GitHub Desktop.
Mock Android TextUtils static method
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment