如何使用属性单元测试自定义视图

时间:2018-02-24 16:52:08

标签: android mockito android-testing custom-view

我无法为自定义视图创建单元测试。我尝试添加一个属性并测试它,如果我的自定义视图类正确。

这是我的测试结果:

@RunWith(AndroidJUnit4.class)
@SmallTest
public class BaseRatingBarMinRatingTest {

    private Context mContext;

    @Before
    public void setUp(){
        mContext = InstrumentationRegistry.getTargetContext();
    }

    @Test
    public void constructor_should_setMinRating_when_attriSetHasOne() throws Exception{
        // 1. ARRANGE DATA
        float minRating = 2.5f;
        AttributeSet as = mock(AttributeSet.class);
        when(as.getAttributeFloatValue(eq(R.styleable.BaseRatingBar_srb_minRating), anyFloat())).thenReturn(minRating);


        // 2. ACT
        BaseRatingBar brb = new BaseRatingBar(mContext, as);


        // 3. ASSERT
        assertThat(brb.getMinRating(), is(minRating));
    }

  // ...

}

哪个得到了这个例外:

java.lang.ClassCastException: android.util.AttributeSet$MockitoMock$1142631110 cannot be cast to android.content.res.XmlBlock$Parser

我尝试像this article那样模仿TypeArray,但我的观点将模拟的上下文视为null。

有没有什么好方法可以为自定义视图创建测试用例?

2 个答案:

答案 0 :(得分:3)

我遇到了类似的问题。和你一样,我想测试自定义视图。这就是我解决它的方法:

public class CustomViewTest {
    @Mock
    private Context context;
    @Mock
    private AttributeSet attributes;
    @Mock
    private TypedArray typedArray;

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
        when(context.obtainStyledAttributes(attributes, R.styleable.CustomView)).thenReturn(typedArray);
        when(typedArray.getInteger(eq(R.styleable.CustomView_customAttribute), anyInt())).thenReturn(23);
    }

    @Test
    public void constructor() {
        CustomView customView = new CustomView(context, attributes);
        assertEquals(23, customView.getCustomAttribute());
    }
}

在我的CustomView类中:

public CustomView(Context context, AttributeSet attrs) {
    super(context, attrs);
    if (attrs != null) {
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CustomView);
        customAttribute = a.getInteger(R.styleable.CustomView_customAttribute, 19);
        a.recycle();
    } else {
        customAttribute = 19;
    }
}

尝试此方法,如果不起作用,请发布确切的错误消息。希望它有所帮助。

答案 1 :(得分:0)

考虑使用Robolectric,因为它消除了对模拟的需求。

AttributeSet as =  Robolectric.buildAttributeSet().addAttribute(R.style.BaseRatingBar_srb_minRating, "2.5f"_.build()
BaseRatingBar brb = new BaseRatingBar(mContext, as);