Edit #4 & #5:在Robolectric 3.*,他们拆分了片段起始函数。
对于支持片段,您需要将dependency 添加到您的build.gradle:
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 for support and regular fragments。您可以使用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:如果您正在使用支持片段 (one that supports regular activities/fragments should be in the next release),则会有一个新的助手:
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();
}
}