Edit #4 & #5: 在
Robolectric 3.* 版本中,他们将片段启动函数进行了拆分。
对于支持片段,您需要在
build.gradle
中添加
dependency。
testCompile "org.robolectric:shadows-supportv4:3.8"
导入:org.robolectric.shadows.support.v4.SupportFragmentTestUtil.startFragment;
对于平台片段,您不需要此依赖项。导入:import static org.robolectric.util.FragmentTestUtil.startFragment;
它们都使用相同的名称startFragment()
。
import static org.robolectric.shadows.support.v4.SupportFragmentTestUtil.startFragment;
@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class)
public class YourFragmentTest
{
@Test
public void shouldNotBeNull() throws Exception
{
YourFragment fragment = YourFragment.newInstance();
startFragment( fragment );
assertNotNull( fragment );
}
}
编辑 #3: Robolectric 2.4拥有支持和常规片段的
API。您可以使用
newInstance()
模式或在构建
Fragment
时使用构造函数。
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.assertNotNull;
import static org.robolectric.util.FragmentTestUtil.startFragment;
@RunWith(RobolectricGradleTestRunner.class)
public class YourFragmentTest
{
@Test
public void shouldNotBeNull() throws Exception
{
YourFragment fragment = new YourFragment();
startFragment( fragment );
assertNotNull( fragment );
}
}
编辑 #2:如果您正在使用支持片段(一个支持常规活动/片段的将在下一个版本中发布),则会有一个新的助手可用:
import static org.robolectric.util.FragmentTestUtil.startFragment;
@Before
public void setUp() throws Exception
{
fragment = YourFragment.newInstance();
startFragment( fragment );
}
编辑:如果你升级到 Robolectric 2.0:
public static void startFragment( Fragment fragment )
{
FragmentActivity activity = Robolectric.buildActivity( FragmentActivity.class )
.create()
.start()
.resume()
.get();
FragmentManager fragmentManager = activity.getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add( fragment, null );
fragmentTransaction.commit();
}
原始回答
正如其他评论者建议的那样,您需要使用片段管理器(而不是调用上述生命周期方法)。
@RunWith(MyTestRunner.class)
public class YourFragmentTest
{
@Test
public void shouldNotBeNull() throws Exception
{
YourFragment yourFragment = new YourFragment();
startFragment( yourFragment );
assertNotNull( yourFragment );
}
我创建了一个测试运行器,并编写了一个函数,可以为我启动一个片段,以便我可以在任何地方使用它。
public class MyTestRunner extends RobolectricTestRunner
{
public MyTestRunner( Class<?> testClass ) throws InitializationError
{
super( testClass );
}
public static void startFragment( Fragment fragment )
{
FragmentManager fragmentManager = new FragmentActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add( fragment, null );
fragmentTransaction.commit();
}
}