2015-11-12

[Mokito] 使用Mokito寫測試的筆記 (Note for writing test cases by Mokito)


Test Class Template
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricGradleTestRunner;
import org.robolectric.annotation.Config;

import static android.os.Build.VERSION_CODES.LOLLIPOP;

@Config(sdk = LOLLIPOP, constants = BuildConfig.class)
@RunWith(RobolectricGradleTestRunner.class)
public class MyTest {

    // something to mock
    @Mock TypeA A;
    @Spy TypeB B = new TypeB();
    // ...

    // Set up
    @Before public void setUp() throws Exception {
        initMocks(this);    // create mock objects, ex. A and B above
        // ... do so other init things
    }

    // Tear down
    @After public void tearDown() {
        // ... do so tear down things
    }

    // Test Case (which should not throw exception)
    @Test public void testCase1() throws Exception {
        // do something
    }

    // Test Case (expect exception)
    @Test(expected=YouExceptException.class) public void testException1() {
       // something would throw YouExceptException.class exception
    }

    // Test Case (expect exception)
    @Test public void testException2() throws Exception {
        try {
            // something should throw exception
            // import org.assertj.core.api.Assertions;
            Assertions.failBecauseExceptionWasNotThrown(YouExpectException.class);
        } catch (YouExpectException e) {
        }
        // verify other things here
    }

    // Test Case (with timeout)
    @Test(timeout=100) public void infinity() {
       // something should not run longer than 100ms
    }
    
}

2015-11-02

[Android][RxJava] Run something async on non-UI thread, then back to MainThread to do something after that.


當你有某些東西要Async地在background、而且是non-UI thread運作
(例如:Android要連接網路Network、http之類的時候)

但是做完又要回到Main Thread
(例如:從網路or anywhere拿到資料之後要更新UI)

就可以用以下的Pattern來寫


Async.fromCallable(new Callable() {
    // T is the type you want to send back to MainThread
    @Override public T call() throws Exception {
        // do something that you want it async run on Schedulers.io()
        return [object in type T];
    }
}, Schedulers.io())  
// specify the thread you want async work to run on it, here we use Schedulers.io()

    .observeOn(AndroidSchedulers.mainThread())  // then back to MainThread
    .subscribe(new Subscriber() {
        // run on MainThread
        @Override public void onCompleted() {

        }

        @Override public void onError(Throwable e) {

        }

        @Override public void onNext(T obj) {

        }
    });