gpt4 book ai didi

android - 使用 mockito 测试使用上下文的函数

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:02:28 24 4
gpt4 key购买 nike

Android Studio 2.1.2

我正在尝试测试调用 loadNewsFeedgetJsonFromResource。我希望能够测试 2 种情况,一种是 loadNewsFeed 将返回一个空字符串,另一种是返回一些 json 字符串。

所以我试图模拟 loadNewsFeed 函数以返回一个空字符串。但是,当调用具体的 getJsonFromResource 时,它将调用真正的 loadNewsFeed 并导致空指针异常。这是我在解释我在做什么的测试评论中尝试过的:

@Test
public void shouldFailIfJSONStringIsEmpty() throws Exception {
/* Mock Context class */
Context context = mock(Context.class);
/* initialize the concrete parseNewsFeed passing in the fake context */
ParseNewsFeed parseNewsFeed = new ParseNewsFeed(context);
/* Create a mock of the parseNewsFeed so a fake call to loadNewsFeed will return an empty string */
ParseNewsFeed mockParseNewsFeed = mock(ParseNewsFeed.class);
/* Mock the events that will be verified */
ParseNewsFeedContract.Events<Status> mockEvents = mock(ParseNewsFeedContract.Events.class);

/* Return an empty string when loadNewsFeed is called */
when(mockParseNewsFeed.loadNewsFeed()).thenReturn("");

/* Called the concrete getJsonFromResource */
parseNewsFeed.getJsonFromResource(mockEvents);

/* verify that onNewsFailure was called once and onNewsSuccess was never called */
verify(mockEvents, times(1)).onNewsFailure(anyString());
verify(mockEvents, never()).onNewsSuccess(any(Status.class));
}

这是我要测试的类(class)。

public class ParseNewsFeed implements ParseNewsFeedContract {
private Context mContext;

public ParseNewsFeed(Context context) {
if(context != null) {
Timber.d("mContext != null");
mContext = context;
}
}

/**
* Get the json from the local resource file and add to the cache to save loading each time
* @return the json in string representation
*/
@Override
public void getJsonFromResource(Events<Status> events) {
/* Get the json in string format */
final String jsonString = loadNewsFeed();

/* Check that is contains something */
if(!jsonString.isEmpty()) {
try {
final Status status = new Gson().fromJson(jsonString, Status.class);
if(status != null) {
Timber.d("url: %s", status.getResults().get(0).getMultimedia().get(0).getUrl());
events.onNewsSuccess(status);
}
else {
Timber.e("status == null");
events.onNewsFailure("Failed to get results from json");
}
}
catch (JsonSyntaxException e) {
Timber.e("Invalid JSON: %s", e.getMessage());
events.onNewsFailure(e.getMessage());
}
}
}

/**
* Opens and reads from the news_list and writes to a buffer
* @return return the json representation as a string or a empty string for failure
*/
public String loadNewsFeed() {
InputStream inputStream = mContext.getResources().openRawResource(R.raw.news_list);
Writer writer = new StringWriter();
char[] buffer = new char[1024];

try {
InputStreamReader inputReader = new InputStreamReader(inputStream, "UTF-8");
BufferedReader bufferReader = new BufferedReader(inputReader);
int n;
while ((n = bufferReader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}

inputStream.close();
}
catch (IOException ioException) {
return "";
}

return writer.toString();
}
}

最佳答案

首先,您的原始代码不起作用的原因是因为您的两个对象 parseNewsFeedmockParseNewsFeed 之间没有关系,因此您所做的 stub 当您调用 parseNewsFeed.getJsonFromResource(mockEvents) 时,mockParseNewsFeed 没有任何效果。按照 David Wallace 的建议使用 spy 会奏效,但如果我是你,我会以不同的方式重写代码,以使其更易于测试。

一个观察是 loadNewsFeed() 方法中的代码似乎与 ParseNewsFeed 类没有很强的关系,所以我将这段代码提取到一个对象(例如 NewsFeedLoader),然后将此对象作为 ParseNewsFeed 类的依赖项。然后您可以轻松地模拟此 Loader(返回 "" 或您在传递 Context 和可能的 R. raw.news_list id)。使用此 Loader 类,您甚至可以将它与 ParseNewsFeed 分开进行单元测试,并能够根据需要改进 Loader(例如一种读取原始资源的更好方法)而不影响 ParseNewsFeed 类。

关于android - 使用 mockito 测试使用上下文的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38734073/

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