gpt4 book ai didi

android - 如何使用属性对自定义 View 进行单元测试

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:18:06 26 4
gpt4 key购买 nike

我在为自定义 View 创建单元测试时遇到问题。我尝试添加一个属性并测试它是否我的自定义 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。

有什么好的方法可以为自定义 View 创建测试用例吗?

最佳答案

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

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

关于android - 如何使用属性对自定义 View 进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48965231/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com