顯示包含「AssertJ」標籤的文章。顯示所有文章
顯示包含「AssertJ」標籤的文章。顯示所有文章

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
    }
    
}