Thursday, 9 July 2015

android unit test



http://stackoverflow.com/questions/30057310/can-powermockito-be-used-with-android-studio-1-2

dependencies {
    testCompile 'junit:junit:4.12'
    testCompile 'org.mockito:mockito-core:2.0.5-beta'
    testCompile 'com.android.support:support-v4:22.0.0'
    testCompile ('org.powermock:powermock-api-mockito:1.6.2') {
        exclude module: 'hamcrest-core'
        exclude module: 'objenesis'
    }
    testCompile ('org.powermock:powermock-module-junit4:1.6.2') {
        exclude module: 'hamcrest-core'
        exclude module: 'objenesis'
    }
}



Finally, I realise that,  I cannot make my unit test works with mockito and powermock.


So I changed to easymock and powermock:


// EasyMock
testCompile 'org.easymock:easymock:3.3.1'
// PowerMock
testCompile 'org.powermock:powermock-core:1.6.2'
testCompile 'org.powermock:powermock-module-junit4:1.6.2'
// PowerMock + EasyMock extension
testCompile 'org.powermock:powermock-api-easymock:1.6.2'
// Junit
testCompile 'junit:junit:4.12'



import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import static org.easymock.EasyMock.expect;
import static org.junit.Assert.assertEquals;
import static org.powermock.api.easymock.PowerMock.mockStatic;
import static org.powermock.api.easymock.PowerMock.replay;
import static org.powermock.api.easymock.PowerMock.verify;
/**
* Created by peterwang on 08/07/15.
*/
@RunWith(PowerMockRunner.class)
@PrepareForTest( { SimpleStaticService.class })
public class ServicesRegestoryTest {
@Test
public void testGetService() throws Exception {
mockStatic(SimpleStaticService.class);
expect(SimpleStaticService.say("aa")).andReturn("a");
replay(SimpleStaticService.class);
assertEquals("a", SimpleStaticService.say("aa"));
}
}




/**
* Created by peterwang on 08/07/15.
*/
public class SimpleStaticService {
public static String say(final String string) {
return "Hello " + string;
}
}



The difficult part is if you test "SimpleStaticService" , this class should be "clean",  don't call UI or other static functions. (other static functions will cause you further static mocking)







https://code.google.com/p/powermock/wiki/GettingStarted


https://code.google.com/p/powermock/wiki/MockitoUsage13


http://blog.burrowsapps.com/2015/05/how-to-test-android-with.html

No comments:

Post a comment