本文介绍了小样帐户ActivityInstrumentationTestCase2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在我的活动,我得到了的onCreate帐户()
:
In my Activity, I get accounts in onCreate()
:
public void MyActivity extends Activity{
...
private Account[] accounts;
@Override
protected void onCreate(){
accounts = AccountManager.get(this).getAccounts();
}
...
}
在测试项目
现在,我是单元测试 MyActivity
:
public class MyActivityTest extends ActivityInstrumentationTestCase2<MyActivity> {
...
@Override
protected void setUp() throws Exception{
super.setUp();
//How to mock up the accounts in system so that some fake accounts could be used
}
...
}
在我上面的测试情况下,我想用一些假户口,我怎么能小样帐户,这样 AccountManager.get(本).getAccounts() ;
返回我的项目,那些嘲笑帐户下测试
In my above test case, I would like to use some fake accounts, how could I mock up the accounts so that AccountManager.get(this).getAccounts();
returns those mocked accounts in my project under test?
推荐答案
试试这个code:
import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.any;
import static org.powermock.api.mockito.PowerMockito.mockStatic;
import static org.powermock.api.mockito.PowerMockito.when;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
@RunWith(PowerMockRunner.class)
@PrepareForTest(AccountManager.class)
public class MyActivityTest extends ActivityInstrumentationTestCase2<MyActivity> {
{
@Mock
public MyActivity myActivity;
@Mock
AccountManager accountManager;
@Before
public void setUp() throws Exception{
MockitoAnnotations.initMocks(this);
}
@Test
public void mocking() {
mockStatic(AccountManager.class);
when(AccountManager.get(any(MyActivity.class))).thenReturn(accountManager);
when(accountManager.getAccounts()).thenReturn(new Account[] {});
MyActivity activity = new MyActivity();
activity.onCreate();
assertEquals(0, activity.getAccounts().length);
}
@Test
public void withoutMocking() {
MyActivity activity = new MyActivity();
activity.onCreate();
assertEquals(2, activity.getAccounts().length);
}
}
这篇关于小样帐户ActivityInstrumentationTestCase2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!