티스토리 뷰

Mock Solution

JUnit 의 TestCase class에서는 Android 관련 API를 쓰지 못한다. 그래서, 이럴경우에 우린 Mockup을 만들어서 쓴다.
대표적인 PowerMockito를  static class를 Mock할때 쓴다.

Add two lines above your test case class,

@RunWith(PowerMockRunner.class)
@PrepareForTest(TextUtils.class)
public class YourTest
{

}

And the setup code

@Before
public void setup() {
    PowerMockito.mockStatic(TextUtils.class);
    PowerMockito.when(TextUtils.isEmpty(any(CharSequence.class))).thenAnswer(new Answer<Boolean>() {
        @Override
        public Boolean answer(InvocationOnMock invocation) throws Throwable {
            CharSequence a = (CharSequence) invocation.getArguments()[0];
            return !(a != null && a.length() > 0);
        }
    });
}

위의 코드가 TextUtils.isEmpty() 메소드를 Mock하는 코드이다.

Also, add dependencies in app.gradle files.

testCompile "org.powermock:powermock-module-junit4:1.6.2"
testCompile "org.powermock:powermock-module-junit4-rule:1.6.2"
testCompile "org.powermock:powermock-api-mockito:1.6.2"
testCompile "org.powermock:powermock-classloading-xstream:1.6.2"

아니면, Mock을 써서 구현하기가 너무 귀찮을때는 Simpler Solution을 쓰자. package명을 android와 똑같이 줘서 해결하는 방법이다.

Simple Solution

In your src/test/java folder, add android.text package and create TextUtils.java

public class TextUtils {
public static boolean isEmpty(CharSequence str) {
return str == null || str.length() == 0;
}
}


'Android > Android TIP' 카테고리의 다른 글

Implicit Intent broadcast using a custom permission  (0) 2018.04.10
Processing Ordered Broadcasts  (0) 2013.08.21
DP and SP  (0) 2013.07.04
코딩 팁  (0) 2012.10.06
Android TIP  (0) 2012.09.28
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함