본문

170731(월) - Building Local Unit Tests

Building Local Unit Tests


Local unit tests

- 만약 unit test가 dependencies가 없고, Android 에 대해 simple dependencies만 있는 경우 local development machine에서 test를 진행해야 한다.


- test가 실행될 때마다 target app & unit test code가 physical device or emulator에 매번 loading되는 overhead를 피할 수 있으므로 효율적이다.


- 위와같은 이유로 execution time이 매우 줄어든다.

- Mockito같은 mocking framework를 사용하여 모든 dependency relationships를 충족시킨다.



Set up your testing environment

- project에 이미 'module-name/src/test/java/.' 가 있으며, 여기에 local unit test를 위한 소스를 저장한다.

- JUnit 4 framework의 standards APIs를 사용하려면 testing dependencies를 구성해야 한다.

- Android dependencies와 interact해야 하는 경우 Mockito library를 사용하여 local unit test를 simple하게 할 수 있다.


dependencies {
   
// Required -- JUnit 4 framework
    testCompile
'junit:junit:4.12'
   
// Optional -- Mockito framework
    testCompile
'org.mockito:mockito-core:1.10.19'
}



Create a local unit test class

- local unit test class는 JUnit 4 test class로 작성되어야 한다.

- JUnit 4 test class를 작성하려면 one or more test methods가 들어있는 Java class를 작성해야 한다.

- test method는 @Test annotation으로 시작하고 single functionality in the component를 exercise하고 verify하는 코드를 포함한다.


import org.junit.Test;
import java.util.regex.Pattern;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

public class EmailValidatorTest {

   
@Test
   
public void emailValidator_CorrectEmailSimple_ReturnsTrue() {
        assertThat
(EmailValidator.isValidEmail("name@email.com"), is(true));
   
}
   
...
}

- app의 component가 expected results를 반환하는지 test하려면 junit.Assert() method를 사용하여 validation checks(or assertions)를 수행하여 expected value와 비교.


- test를 readable하게 하기 위해 Hamcrest matchers(such as the is() & equalTo() method)를 사용하여 returned result와 expected result를 비교할 수 있다.



Mock Android dependencies

- Android Plug-in for Gradle은 실제 코드를 포함하지 않는 modified version of the android.jar library에 대해서 local unit test를 수행한다.


- Android class에 대한 method call은 throw exception!

- 이는 code만 test하고 explicitly 하게 mocked 하지 않은 Android platform의 특정 동작에 의존하지 않게 하기 위한것이다.

- mocking framework를 사용하여 external dependencies를 stub out 하고 component가 예상되는 방식으로 dependency와 상호작용 하는지 쉽게 테스트 가능하다.


- Mockito mocking framework(1.9.5 higher)는 Android unit testing과 호환된다.

- Mockito를 사용하면 호출시 특정값을 return하도록 mock object를 구성 가능하다.


- Mockito mocking framework Programming model

1. include Mockito library dependency your build.gradle file

2. test class 시작 부분에 @RunWith(MockitoJUnitRunner.class) annotation을 추가. 이 annotation은 test runner에게 framework 사용법이 올바른지 화인하고 mock object initialization를 단순화 한다.


3. Android dependency를 위한 mock object를 만드려면, field declaration 앞에 @Mock annotation을 추가.

4. dependency 동작을 stub하기 위하여 when() or thenReturn() method를 사용하여 조건이 충족될 때 조건과 return 값을 지정 가능


ex)


import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.CoreMatchers.*;
import static org.mockito.Mockito.*;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import android.content.SharedPreferences;

@RunWith(MockitoJUnitRunner.class)
public class UnitTestSample {

   
private static final String FAKE_STRING = "HELLO WORLD";

   
@Mock
   
Context mMockContext;

   
@Test
   
public void readStringFromContext_LocalizedString() {
       
// Given a mocked Context injected into the object under test...
       
when(mMockContext.getString(R.string.hello_word))
               
.thenReturn(FAKE_STRING);

       
ClassUnderTest myObjectUnderTest = new ClassUnderTest(mMockContext);

       
// ...when the string is returned from the object under test...
       
String result = myObjectUnderTest.getHelloWorldString();

       
// ...then the result should be the expected one.
        assertThat
(result, is(FAKE_STRING));
   
}
}

Mockito API referencesample code.



Error : "Method ... not mocked"

- android.jar에 포함되지 않은 method 호출 시 exception이 throw된다.

- 만약 이게 문제가 된다면 아래 코드를 top-level build.gradle file에 넣어 null or 0 가 리턴되도록 조정 가능하다.

- 이 option을 넣는것은 regressions를 유발할 수 있으므로 최후의 수단으로만 사용할 것.


android {
 
...
  testOptions
{
    unitTests
.returnDefaultValues = true
 
}
}


Run Local Unit Tests

- single test, open the Project window, and right click test and click Run.

- all method in a class, right click or method in the test file and click Run.

- all test in a directory, right click on the directory and select Run tests.


Android Plugin for Gradle은 

1. default directory (src / test / java) 에 있는 local unit test code를 compile

2. test app build

3. executes locally, using the default test runner class.

4. displays the result in the Run window




공유

댓글

고뇌하는 식빵남아

design by tokiidesu. powerd by AXZ.