Robolectric3でDrawerLayoutをテスト
タイトル通り、DrawerLayoutをRobolectric3でテストするメモ
package kinjouj.app.oretter;
import java.lang.reflect.Method;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.view.ViewGroup;
import android.widget.TextView;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricGradleTestRunner;
import org.robolectric.RuntimeEnvironment;
import static org.junit.Assert.*;
import static org.hamcrest.Matchers.*;
@RunWith(RobolectricGradleTestRunner.class)
public class DrawerLayoutTest {
private static final int MP = ViewGroup.LayoutParams.MATCH_PARENT;
// class MainActivity extends AppCompatActivity
private MainActivity activity;
private DrawerLayout drawerLayout;
private ActionBarDrawerToggle actionBarDrawer;
@Before
public void setUp() {
activity = Robolectric.buildActivity(MainActivity.class).attach().get();
drawerLayout = new DrawerLayout(RuntimeEnvironment.application);
drawerLayout.addView(
new TextView(RuntimeEnvironment.application),
0,
new DrawerLayout.LayoutParams(MP, MP, GravityCompat.START)
);
actionBarDrawer = new ActionBarDrawerToggle(
activity,
drawerLayout,
new Toolbar(RuntimeEnvironment.application),
R.string.drawer_open,
R.string.drawer_close
);
drawerLayout.setDrawerListener(actionBarDrawer);
actionBarDrawer.syncState();
}
@Test
public void test() throws Exception {
assertThat(drawerLayout.isDrawerOpen(GravityCompat.START), is(false));
drawerLayout.openDrawer(GravityCompat.START);
assertThat(drawerLayout.isDrawerOpen(GravityCompat.START), is(true));
drawerLayout.closeDrawer(GravityCompat.START);
assertThat(drawerLayout.isDrawerOpen(GravityCompat.START), is(false));
// やらなくてもいいけどActionBarDrawerToggle.toggleメソッドでも開閉は可能
Method method = ActionBarDrawerToggle.class.getMethod("toggle", null);
method.invoke(actionBarDrawer, null);
assertThat(drawerLayout.isDrawerOpen(GravityCompat.START), is(true));
}
}
DrawerLayoutのインスタンスを生成するだけではopenDrawer等のメソッドを実行するとエラーになるのでaddView等をしておく必要がある模様