我很难为我的自定义视图创建单元测试。我尝试添加一个属性并进行测试,如果我的自定义视图类正确。
这是我的测试的样子:
@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
我尝试像本文一样嘲笑Typearray,但是我的观点将模拟的上下文视为无效。
有什么好方法可以为自定义视图创建测试用例吗?
考虑使用robolectric,因为它消除了对模拟的需求。
AttributeSet as = Robolectric.buildAttributeSet().addAttribute(R.style.BaseRatingBar_srb_minRating, "2.5f").build()
BaseRatingBar brb = new BaseRatingBar(mContext, as);
我有一个类似的问题。像您一样,我想测试自定义视图。这就是我解决的方式:
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;
}
}
尝试此方法,并发布确切的错误消息,如果它不起作用。希望它有帮助。