Skip to content

Instantly share code, notes, and snippets.

@esmasui
Created November 7, 2013 04:21
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save esmasui/7348920 to your computer and use it in GitHub Desktop.
Save esmasui/7348920 to your computer and use it in GitHub Desktop.
Fragment unit test
package com.uphyca.fragmenttest;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.test.ActivityUnitTestCase;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
/**
* Created by masui on 11/7/13.
*/
public class FragmentTest extends ActivityUnitTestCase<FragmentTest.MyActivity> {
public static class MyActivity extends FragmentActivity {
}
public static class FragmentUnderTest extends Fragment {
public boolean created;
public boolean started;
public boolean viewCreated;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
created = true;
}
@Override
public void onStart() {
super.onStart();
started = true;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
TextView text = new TextView(getActivity());
text.setId(android.R.id.text1);
text.setText("hoge");
return text;
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
viewCreated = true;
}
}
FragmentManager mFragmentManager;
public FragmentTest() {
super(MyActivity.class);
}
@Override
protected void setUp() throws Exception {
super.setUp();
startActivity(new Intent(Intent.ACTION_MAIN), null, null);
mFragmentManager = getActivity().getSupportFragmentManager();
}
public void testFragment() throws Exception {
mFragmentManager.beginTransaction()
.replace(android.R.id.content, new FragmentUnderTest())
.commit();
mFragmentManager.executePendingTransactions();
FragmentUnderTest underTest = (FragmentUnderTest) mFragmentManager.findFragmentById(android.R.id.content);
assertNotNull(underTest);
getInstrumentation().callActivityOnStart(getActivity());
getInstrumentation().callActivityOnResume(getActivity());
mFragmentManager.executePendingTransactions();
assertTrue(underTest.created);
assertTrue(underTest.started);
assertTrue(underTest.viewCreated);
assertEquals("hoge", TextView.class.cast(underTest.getView()
.findViewById(android.R.id.text1))
.getText());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment