gpt4 book ai didi

java - Mockito 想要但没有调用实用程序类

转载 作者:行者123 更新时间:2023-11-30 10:12:39 27 4
gpt4 key购买 nike

我正在为我的应用程序中的类进行单元测试,它只是一个简单的类,我认为我做的一切都是正确的,但测试失败了

Wanted but not invoked: mContextWeakReference.get(); -> at rahmat.com.app.utility.backwardcompatibility.StringResourceUtilTest.getString(StringResourceUtilTest.java:40) Actually, there were zero interactions with this mock.

这是要测试的类

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));
}}

非常感谢任何帮助,谢谢

最佳答案

你的 StringUtil 类总是创建一个新的 mContextWeakReference 对象,即使你正在创建它,它也不会自动注入(inject)(因为你使用 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?

关于java - Mockito 想要但没有调用实用程序类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51778980/

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