【问题标题】:Mock up account in ActivityInstrumentationTestCase2ActivityInstrumentationTestCase2 中的模拟帐户
【发布时间】:2013-10-17 20:37:15
【问题描述】:

在我的 Activity 中,我获得了 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(this).getAccounts(); 在我的测试项目中返回那些模拟账户?

【问题讨论】:

  • 我也可以真的为此使用答案 - 只要该答案不仅仅是一个有根据的猜测,例如“向它扔 Mockito!”

标签: android performance unit-testing junit android-account


【解决方案1】:

试试这个代码:

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

}

【讨论】:

  • 您是如何设法在 Android 中运行 PowerMock 的?据我所知,在 Dalvik Runtime 上是不可能的
猜你喜欢
  • 1970-01-01
  • 2013-07-18
  • 2011-05-19
  • 1970-01-01
  • 2017-12-12
  • 2013-02-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多