gpt4 book ai didi

android - 在 ActivityInstrumentationTestCase2 中模拟账户

转载 作者:太空宇宙 更新时间:2023-11-03 11:14:14 25 4
gpt4 key购买 nike

在我的 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(); 在我的测试项目中返回那些模拟帐户?

最佳答案

试试这段代码:

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 - 在 ActivityInstrumentationTestCase2 中模拟账户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19289770/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com