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

问题描述 投票:2回答:1

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

这是我的测试的样子:

@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。

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

android mockito android-testing custom-view
1个回答
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;
    }
}

尝试这种方法,并发布确切的错误消息,如果它不起作用。希望能帮助到你。

© www.soinside.com 2019 - 2024. All rights reserved.