我正在对我的应用程序中的类进行单元测试,这只是一个简单的类,我以为我所做的一切都正确,但是测试失败,说明
想要但不被调用: mContextWeakReference.get(); ->在rahmat.com.app.utility.backwardcompatibility.StringResourceUtilTest.getString(StringResourceUtilTest.java:40) 实际上,与该模拟游戏的互动为零。
这是要测试的课程
public class StringResourceUtil {
private static StringResourceUtil sInstance;
private WeakReference<Context> mContextWeakReference;
public static StringResourceUtil getInstance() {
return sInstance;
}
@Inject
public StringResourceUtil(Context context) {
mContextWeakReference = new WeakReference<>(context);
sInstance = this; //NOSONAR
}
public String getString(int resId) {
return mContextWeakReference.get().getString(resId);
}}
这是我做的单元测试
public class StringResourceUtilTest {
private StringResourceUtil mResourceUtil;
@Mock
private Context mContext;
@Mock
private WeakReference<Context> mContextWeakReference;
@Before
public void setUp(){
MockitoAnnotations.initMocks(this);
mResourceUtil = new StringResourceUtil(mContext);
}
@Test
public void getString() {
int resId = 123;
mResourceUtil.getString(resId);
verify(mContextWeakReference).get().getString(eq(resId));
}}
任何帮助将不胜感激,谢谢
答案 0 :(得分:1)
您的StringUtil
类始终在创建mContextWeakReference
对象的新对象,即使您正在创建它,它也不会自动注入(因为您使用injectMock
但没有使用在这里,因为新对象的创建总是在内部进行的。
public class StringResourceUtilTest {
private StringResourceUtil mResourceUtil;
@Mock
private Context mContext;
@Before
public void setUp(){
MockitoAnnotations.initMocks(this);
mResourceUtil = new StringResourceUtil(mContext);
// setup mock return type
// mock objects are not real,so need to moeck the behavior of method as well
when(mContext.getString(R.string.a123)).thenReturn("123");
}
@Test
public void getString() {
int resId = R.string.a123;
// check the return type
assertEquals("123",mResourceUtil.getString(resId));
}
}
注意:要验证内部工作原理,请阅读
What is the difference between mocking and spying when using Mockito?
答案 1 :(得分:0)
由于您在构造函数中创建了mContextWeakReference = new WeakReference<>(context);
,所以它在StringResourceUtil
中将永远不会成为模拟对象。
您可以使用
设置准备好的模拟mContextWeakReference
org.springframework.test.util.ReflectionTestUtils.setField(mResourceUtil , "mContextWeakReference", mContextWeakReference);
否则,您应该将StringResourceUtil
类修改为可测试的