Nice programing

Robolectric으로 조각을 어떻게 테스트 할 수 있습니까?

nicepro 2020. 12. 26. 16:35
반응형

Robolectric으로 조각을 어떻게 테스트 할 수 있습니까?


Robolectric.shadowOf(Fragment)방법과 ShadowFragment클래스 가 있다는 것을 알고 있으며 문서에 나열되어 있지 않다고 생각했지만 작동하도록 만들 수 없습니다.

myFragment = new MyFragment();
myFragment.onCreateView(LayoutInflater.from(activity), (ViewGroup) activity.findViewById(R.id.container), null);
myFragment.onAttach(activity);
myFragment.onActivityCreated(null); 

저는 API 레벨 13 (Honeycomb)으로 작업하고 있습니다.

감사.


편집 # 4 & # 5 : Robolectric 3. * 에서는 조각 시작 기능을 분할합니다.

지원 조각의 경우에 종속성추가해야 합니다 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가 있습니다. 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();
    }
}

너희들은 모두이 일을 열심히하고있다. FragmentTestUtil을 사용하십시오.

FragmentTestUtil.startFragment(yourfragment);

지원 조각이 모듈로 이동되었습니다.

그림자 지원 v4

(2015 년 7 월 현재 Robolectric v3.0)

app / build.gradle에 gradle 종속성을 추가합니다.

testCompile 'org.robolectric:shadows-support-v4:3.0'

그런 다음 Robolectric 테스트 Java 클래스로 가져옵니다.

import org.robolectric.shadows.support.v4.SupportFragmentTestUtil;

그런 다음 테스트를 위해 support-v4 조각을 시작하고 사용할 수 있습니다.

@Test
public void minimalFragmentTest() throws Exception {
    MyFunFragment fragment = new MyFunFragment();
    SupportFragmentTestUtil.startVisibleFragment(fragment);
    assertThat(fragment.getView()).isNotNull();
}

참조 :


I'm pretty sure you have to create a FragmentTransaction using the FragmentManager, then it will work.


I just wanted to add that in Robolectric 2.0 even after doing:

activity = Robolectric.buildActivity(FragmentActivity.class).create().start().resume().get();
fragment.show(activity.getSupportFragmentManager(), null);
fragment.getDialog();  //This stills returns null

It still returned null for me. what I did was to add activity.getSupportFragmentManager().executePendingTransaction(); and it worked.

It seems robolectric doesn't run this for some reason. it seems that maybe the Looper is paused or something. any way this worked for me and it looks like this:

activity = Robolectric.buildActivity(FragmentActivity.class).create().start().resume().get();
fragment.show(activity.getSupportFragmentManager(), null);
activity.getSupportFragmentManager().executePendingTransactions();
fragment.getDialog();

SupportFragmentTestUtil.startFragment(fragment, AppCompatActivity::class.java)

If the activity is extending AppCompatActivity

This is using Kotlin

ReferenceURL : https://stackoverflow.com/questions/11333354/how-can-i-test-fragments-with-robolectric

반응형