Example code for blog post: Mocking Static Methods in Android: Let's Wrap it up.
// Example 1 - Test that fails | |
public class ClassUnderTest { | |
public String methodUnderTest(String str) | |
{ | |
if (PhoneNumberUtils.isGlobalPhoneNumber(str)) | |
{ | |
return "yes"; | |
} | |
else | |
{ | |
return "no"; | |
} | |
} | |
} | |
@RunWith(JUnit4.class) | |
public class TestThatFails { | |
private ClassUnderTest classUnderTest; | |
@Before | |
public void setup() { | |
classUnderTest = new ClassUnderTest(); | |
} | |
@Test | |
public void testTheClass() { | |
String result = classUnderTest.methodUnderTest("1234"); | |
assertEquals("yes", result); | |
} | |
} | |
// Example 2 - Test with wrapper class | |
public class PhoneNumberUtilsWrapper { | |
public boolean isGlobalPhoneNumber(String phoneNumber) | |
{ | |
return PhoneNumberUtils.isGlobalPhoneNumber(phoneNumber); | |
} | |
} | |
public class ClassUnderTestWithWrapper { | |
private PhoneNumberUtilsWrapper wrapper; | |
public ClassUnderTestWithWrapper(PhoneNumberUtilsWrapper wrapper) { | |
this.wrapper = wrapper; | |
} | |
public String methodUnderTest(String str) | |
{ | |
if (wrapper.isGlobalPhoneNumber(str)) | |
{ | |
return "yes"; | |
} | |
else | |
{ | |
return "no"; | |
} | |
} | |
} | |
@RunWith(JUnit4.class) | |
public class TestWithWrapper { | |
@Mock | |
PhoneNumberUtilsWrapper wrapper; | |
private ClassUnderTestWithWrapper classUnderTest; | |
@Before | |
public void setup() { | |
MockitoAnnotations.initMocks(this); | |
classUnderTest = new ClassUnderTestWithWrapper(wrapper); | |
} | |
@Test | |
public void testTheClass() { | |
when(wrapper.isGlobalPhoneNumber(anyString())).thenReturn(true); | |
String result = classUnderTest.methodUnderTest("1234"); | |
assertEquals("yes", result); | |
} | |
} | |
// Example 3 - Test with wrapped method | |
public class ClassUnderTestWithWrappedMethod { | |
public String methodUnderTest(String str) | |
{ | |
if (isGlobalPhoneNumber(str)) | |
{ | |
return "yes"; | |
} | |
else | |
{ | |
return "no"; | |
} | |
} | |
boolean isGlobalPhoneNumber(String phoneNumber) | |
{ | |
return PhoneNumberUtils.isGlobalPhoneNumber(phoneNumber); | |
} | |
} | |
@RunWith(JUnit4.class) | |
public class TestWithWrappedMethod { | |
private ClassUnderTestWithWrappedMethod classUnderTest; | |
private ClassUnderTestWithWrappedMethod classUnderTestSpy; | |
@Before | |
public void setup() { | |
MockitoAnnotations.initMocks(this); | |
classUnderTest = new ClassUnderTestWithWrappedMethod(); | |
classUnderTestSpy = Mockito.spy(classUnderTest); | |
} | |
@Test | |
public void testTheClass() { | |
doReturn(true).when(classUnderTestSpy) | |
.isGlobalPhoneNumber(anyString()); | |
String result = classUnderTestSpy.methodUnderTest("1234"); | |
assertEquals("yes", result); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment