Skip to content

Commit ee738fc

Browse files
test: add remote data source parsing tests
1 parent afbd642 commit ee738fc

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
package com.d4rk.androidtutorials.java.data.source;
2+
3+
import static org.junit.Assert.assertEquals;
4+
import static org.junit.Assert.assertTrue;
5+
import static org.mockito.Mockito.mock;
6+
7+
import android.os.Looper;
8+
9+
import com.android.volley.RequestQueue;
10+
import com.d4rk.androidtutorials.java.data.model.PromotedApp;
11+
12+
import org.json.JSONObject;
13+
import org.junit.Before;
14+
import org.junit.Test;
15+
16+
import java.lang.reflect.Method;
17+
import java.util.List;
18+
19+
public class DefaultHomeRemoteDataSourceTest {
20+
21+
private DefaultHomeRemoteDataSource dataSource;
22+
private Method parseMethod;
23+
24+
@Before
25+
public void setUp() throws Exception {
26+
if (Looper.getMainLooper() == null) {
27+
try {
28+
Method prepareMainLooper = Looper.class.getDeclaredMethod("prepareMainLooper");
29+
prepareMainLooper.setAccessible(true);
30+
prepareMainLooper.invoke(null);
31+
} catch (Exception ignored) {
32+
Looper.prepare();
33+
}
34+
}
35+
RequestQueue queue = mock(RequestQueue.class);
36+
dataSource = new DefaultHomeRemoteDataSource(queue, "https://example.com");
37+
parseMethod = DefaultHomeRemoteDataSource.class.getDeclaredMethod("parseResponse", JSONObject.class);
38+
parseMethod.setAccessible(true);
39+
}
40+
41+
@SuppressWarnings("unchecked")
42+
private List<PromotedApp> invokeParse(JSONObject json) throws Exception {
43+
return (List<PromotedApp>) parseMethod.invoke(dataSource, json);
44+
}
45+
46+
@Test
47+
public void parseResponseFiltersOwnPackages() throws Exception {
48+
String json = "{\"data\":{\"apps\":[" +
49+
"{\"name\":\"App1\",\"packageName\":\"com.example.app1\",\"iconLogo\":\"logo1\"}," +
50+
"{\"name\":\"App2\",\"packageName\":\"com.d4rk.androidtutorials.sample\",\"iconLogo\":\"logo2\"}]}}";
51+
List<PromotedApp> result = invokeParse(new JSONObject(json));
52+
assertEquals(1, result.size());
53+
assertEquals("com.example.app1", result.get(0).getPackageName());
54+
}
55+
56+
@Test
57+
public void parseResponseMalformedJsonReturnsEmptyList() throws Exception {
58+
String json = "{\"data\":{}}";
59+
List<PromotedApp> result = invokeParse(new JSONObject(json));
60+
assertTrue(result.isEmpty());
61+
}
62+
}

0 commit comments

Comments
 (0)