How do I create a shadow class to work around crashes related to custom attributes when testing an Android app with Robolectric?

浪尽此生 提交于 2019-11-30 12:45:56

So I solved this a simple way. Instead of inflating the view as part of my main.xml, I put it in a separate layout file. In my Activity's constructor, I inflated the layout in a protected function. In my test class, I extended the class under test and instead of inflating the view element, I used a boolean to track that the functions as called.

MainActivity.java

public class MainActivity extends FragmentActivity
{
    @Override
    public void onCreate( Bundle savedInstanceState )
    {
        super.onCreate( savedInstanceState );
        setContentView( R.layout.main );
        addOptionsShade();
    }

    protected void addOptionsShade()
    {
        ViewGroup viewGroup = (ViewGroup) findViewById( R.id.main_view );
        View view = getLayoutInflater().inflate( R.layout.options_shade, null );
        viewGroup.addView( view );
    }
}

MainActivityTest.java

@Test
public void shouldHaveOptionsShade() throws Exception
{
    assertTrue( mainActivity.hostileLibraryWasCalled );
}

class TestMainActivity extends MainActivity
{
    boolean hostileLibraryWasCalled = false;

    @Override
    protected void addOptionsShade()
    {
        hostileLibraryWasCalled = true;
    }
}

I removed the shadow class & bindings and put the library back in a sensible place (not in android package).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!