├── app ├── .gitignore ├── src │ ├── main │ │ ├── res │ │ │ ├── values │ │ │ │ ├── config.xml │ │ │ │ ├── styles.xml │ │ │ │ └── strings.xml │ │ │ ├── mipmap-hdpi │ │ │ │ └── ic_launcher.png │ │ │ ├── mipmap-mdpi │ │ │ │ └── ic_launcher.png │ │ │ ├── mipmap-xhdpi │ │ │ │ └── ic_launcher.png │ │ │ ├── mipmap-xxhdpi │ │ │ │ └── ic_launcher.png │ │ │ ├── menu │ │ │ │ └── main.xml │ │ │ └── layout │ │ │ │ └── activity_main.xml │ │ ├── java │ │ │ └── com │ │ │ │ └── andnexus │ │ │ │ └── android │ │ │ │ └── tests │ │ │ │ ├── App.java │ │ │ │ └── MainActivity.java │ │ └── AndroidManifest.xml │ ├── debug │ │ ├── AndroidManifest.xml │ │ └── java │ │ │ └── com │ │ │ └── andnexus │ │ │ └── android │ │ │ └── tests │ │ │ ├── Graph.java │ │ │ └── ActivityTest.java │ ├── test │ │ └── java │ │ │ └── com │ │ │ └── andnexus │ │ │ └── android │ │ │ └── tests │ │ │ └── MainActivityTest.java │ ├── release │ │ └── java │ │ │ └── com │ │ │ └── andnexus │ │ │ └── android │ │ │ └── tests │ │ │ └── Graph.java │ └── androidTest │ │ └── java │ │ └── com │ │ └── andnexus │ │ └── android │ │ └── tests │ │ └── MainActivityTest.java ├── proguard-rules.pro └── build.gradle ├── model ├── .gitignore ├── build.gradle └── src │ ├── main │ └── java │ │ └── com │ │ └── andnexus │ │ └── model │ │ └── Data.java │ └── test │ └── java │ └── com │ └── andnexus │ └── test │ └── model │ └── DataTest.java ├── backend ├── .gitignore ├── build.gradle └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── andnexus │ │ │ └── backend │ │ │ ├── Database.java │ │ │ ├── DataServlet.java │ │ │ └── ResponseBuilder.java │ └── webapp │ │ ├── WEB-INF │ │ └── web.xml │ │ └── index.jsp │ └── test │ └── java │ └── com │ └── andnexus │ └── backend │ └── ResponseBuilderTest.java ├── connect ├── .gitignore ├── gradle.properties ├── src │ ├── test │ │ └── java │ │ │ └── com │ │ │ └── andnexus │ │ │ └── connect │ │ │ ├── ConnectIntegrationTest.java │ │ │ ├── ParserTest.java │ │ │ ├── RequestTest.java │ │ │ └── ConnectTest.java │ └── main │ │ └── java │ │ └── com │ │ └── andnexus │ │ └── connect │ │ ├── Parser.java │ │ ├── Connect.java │ │ └── Request.java └── build.gradle ├── settings.gradle ├── assets ├── android-testing.gif ├── android-testing.mp4 ├── java-connect-tests.png ├── java-connect-jacoco.png └── LICENSE ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── .gitignore ├── gradle.properties ├── .travis.yml ├── gradlew.bat ├── README.md └── gradlew /app/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /model/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /backend/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /connect/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | include ':app', ':connect', ':backend', ':model' 2 | -------------------------------------------------------------------------------- /model/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'java' 2 | 3 | dependencies { 4 | testCompile "junit:junit:4.10" 5 | } -------------------------------------------------------------------------------- /assets/android-testing.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/andnexus/android-testing/HEAD/assets/android-testing.gif -------------------------------------------------------------------------------- /assets/android-testing.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/andnexus/android-testing/HEAD/assets/android-testing.mp4 -------------------------------------------------------------------------------- /assets/java-connect-tests.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/andnexus/android-testing/HEAD/assets/java-connect-tests.png -------------------------------------------------------------------------------- /connect/gradle.properties: -------------------------------------------------------------------------------- 1 | jettyHttpPort=8000 2 | jettyStopPort=8001 3 | jettyScanIntervalSeconds=3 4 | jettyDaemon=true -------------------------------------------------------------------------------- /assets/java-connect-jacoco.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/andnexus/android-testing/HEAD/assets/java-connect-jacoco.png -------------------------------------------------------------------------------- /app/src/main/res/values/config.xml: -------------------------------------------------------------------------------- 1 | 2 | service.andnexus.com 3 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/andnexus/android-testing/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /app/src/main/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/andnexus/android-testing/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/andnexus/android-testing/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/andnexus/android-testing/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/andnexus/android-testing/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.apk 2 | *.ap_ 3 | *.jar 4 | !gradle/wrapper/gradle-wrapper.jar 5 | lint 6 | *.dex 7 | *.class 8 | bin/ 9 | gen/ 10 | classes/ 11 | gen-external-apklibs/ 12 | target 13 | local.properties 14 | .idea 15 | *.iml 16 | .DS_Store 17 | *.swp 18 | *.bak 19 | .gradle 20 | build/ -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Wed Apr 10 15:27:10 PDT 2013 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-2.2.1-all.zip 7 | -------------------------------------------------------------------------------- /app/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | Tests 3 | No data found… 4 | No connection available… 5 | refresh 6 | 7 | -------------------------------------------------------------------------------- /backend/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'java' 2 | apply plugin: 'war' 3 | 4 | dependencies { 5 | 6 | compile project(':model') 7 | compile 'org.json:json:20140107' 8 | compile 'javax.servlet:servlet-api:2.5' 9 | compile 'com.google.guava:guava:18.0' 10 | 11 | testCompile 'junit:junit:4.10' 12 | } -------------------------------------------------------------------------------- /app/src/debug/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /backend/src/main/java/com/andnexus/backend/Database.java: -------------------------------------------------------------------------------- 1 | package com.andnexus.backend; 2 | 3 | import com.andnexus.model.Data; 4 | 5 | public class Database { 6 | 7 | private static final Data[] DATA = {new Data(123), new Data(456)}; 8 | 9 | public Data[] getData() { 10 | return DATA; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /app/src/main/res/menu/main.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 9 | 10 | -------------------------------------------------------------------------------- /model/src/main/java/com/andnexus/model/Data.java: -------------------------------------------------------------------------------- 1 | package com.andnexus.model; 2 | 3 | public class Data { 4 | 5 | private final int mId; 6 | 7 | public Data(int id) { 8 | mId = id; 9 | } 10 | 11 | @Override 12 | public String toString() { 13 | return String.format("%d", getId()); 14 | } 15 | 16 | public int getId() { 17 | return mId; 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /app/src/test/java/com/andnexus/android/tests/MainActivityTest.java: -------------------------------------------------------------------------------- 1 | package com.andnexus.android.tests; 2 | 3 | import org.junit.Before; 4 | import org.junit.Test; 5 | 6 | import static junit.framework.Assert.assertTrue; 7 | 8 | public class MainActivityTest { 9 | 10 | @Before 11 | public void setUp() { 12 | } 13 | 14 | @Test 15 | public void should() { 16 | assertTrue(true); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /app/src/main/java/com/andnexus/android/tests/App.java: -------------------------------------------------------------------------------- 1 | package com.andnexus.android.tests; 2 | 3 | 4 | import android.app.Application; 5 | 6 | public class App extends Application { 7 | 8 | private Graph mGraph; 9 | 10 | @Override 11 | public void onCreate() { 12 | super.onCreate(); 13 | 14 | mGraph = Graph.Initializer.init(this); 15 | } 16 | 17 | public Graph graph() { 18 | return mGraph; 19 | } 20 | 21 | } -------------------------------------------------------------------------------- /backend/src/main/webapp/WEB-INF/web.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Data 5 | com.andnexus.backend.DataServlet 6 | 7 | 8 | Data 9 | /data 10 | 11 | 12 | index.jsp 13 | 14 | -------------------------------------------------------------------------------- /backend/src/main/webapp/index.jsp: -------------------------------------------------------------------------------- 1 | <%@page import="java.util.Date"%> 2 | <%@ page language="java" contentType="text/html; charset=US-ASCII" pageEncoding="US-ASCII"%> 3 | 4 | 5 | 6 | 7 | Backend 8 | 9 | 10 |

Backend is running.

11 |
12 |

Date=<%= new Date() %>

13 | 14 | -------------------------------------------------------------------------------- /backend/src/main/java/com/andnexus/backend/DataServlet.java: -------------------------------------------------------------------------------- 1 | package com.andnexus.backend; 2 | 3 | import java.io.IOException; 4 | 5 | import javax.servlet.http.HttpServlet; 6 | import javax.servlet.http.HttpServletRequest; 7 | import javax.servlet.http.HttpServletResponse; 8 | 9 | public class DataServlet extends HttpServlet { 10 | 11 | public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { 12 | resp.setContentType("application/json"); 13 | resp.getWriter().println(new ResponseBuilder().setData(new Database().getData()).createJson()); 14 | } 15 | } -------------------------------------------------------------------------------- /connect/src/test/java/com/andnexus/connect/ConnectIntegrationTest.java: -------------------------------------------------------------------------------- 1 | package com.andnexus.connect; 2 | 3 | import com.andnexus.model.Data; 4 | 5 | import org.junit.Test; 6 | 7 | import java.util.List; 8 | 9 | import static org.junit.Assert.assertEquals; 10 | 11 | public class ConnectIntegrationTest { 12 | 13 | @Test 14 | public void backendIntegrationTest() throws Exception { 15 | 16 | Connect connect = new Connect("localhost"); 17 | List actual = connect.getData(); 18 | assertEquals(2, actual.size()); 19 | assertEquals(123, actual.get(0).getId()); 20 | assertEquals(456, actual.get(1).getId()); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /app/src/release/java/com/andnexus/android/tests/Graph.java: -------------------------------------------------------------------------------- 1 | package com.andnexus.android.tests; 2 | 3 | import android.content.Context; 4 | 5 | import javax.inject.Singleton; 6 | 7 | import dagger.Component; 8 | 9 | import static com.andnexus.android.tests.MainActivity.Module; 10 | 11 | @Singleton 12 | @Component(modules = {Module.class}) 13 | public interface Graph { 14 | 15 | void inject(MainActivity activity); 16 | 17 | public final static class Initializer { 18 | 19 | public static Graph init(Context context) { 20 | return DaggerGraph.builder() 21 | .module(new Module(context)) 22 | .build(); 23 | } 24 | } 25 | } -------------------------------------------------------------------------------- /app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in /Users/blehejcek/Android/sdk/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class value to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | -------------------------------------------------------------------------------- /app/src/debug/java/com/andnexus/android/tests/Graph.java: -------------------------------------------------------------------------------- 1 | package com.andnexus.android.tests; 2 | 3 | import android.content.Context; 4 | 5 | import javax.inject.Singleton; 6 | 7 | import dagger.Component; 8 | 9 | import static com.andnexus.android.tests.ActivityTest.Module; 10 | 11 | @Singleton 12 | @Component(modules = {Module.class}) 13 | public interface Graph { 14 | 15 | void inject(MainActivity activity); 16 | 17 | void inject(ActivityTest activity); 18 | 19 | public final static class Initializer { 20 | 21 | public static Graph init(Context context) { 22 | System.setProperty("dexmaker.dexcache", context.getCacheDir().getPath()); 23 | return DaggerGraph.builder() 24 | .module(new Module()) 25 | .build(); 26 | } 27 | } 28 | } -------------------------------------------------------------------------------- /backend/src/main/java/com/andnexus/backend/ResponseBuilder.java: -------------------------------------------------------------------------------- 1 | package com.andnexus.backend; 2 | 3 | import com.andnexus.model.Data; 4 | 5 | import org.json.JSONArray; 6 | import org.json.JSONObject; 7 | 8 | public class ResponseBuilder { 9 | 10 | private Data[] mData; 11 | 12 | public final ResponseBuilder setData(Data[] data) { 13 | mData = data; 14 | return this; 15 | } 16 | 17 | public final String createJson() { 18 | final JSONArray array = new JSONArray(); 19 | if (mData != null) { 20 | for (Data item : mData) { 21 | JSONObject object = new JSONObject(); 22 | object.put("id", item.getId()); 23 | array.put(object); 24 | } 25 | } 26 | return new JSONObject().put("data", array).toString(); 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | 3 | # IDE (e.g. Android Studio) users: 4 | # Gradle settings configured through the IDE *will override* 5 | # any settings specified in this file. 6 | 7 | # For more details on how to configure your build environment visit 8 | # http://www.gradle.org/docs/current/userguide/build_environment.html 9 | 10 | # Specifies the JVM arguments used for the daemon process. 11 | # The setting is particularly useful for tweaking memory settings. 12 | # Default value: -Xmx10248m -XX:MaxPermSize=256m 13 | # org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 14 | 15 | # When configured, Gradle will run in incubating parallel mode. 16 | # This option should only be used with decoupled projects. More details, visit 17 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 18 | # org.gradle.parallel=true -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 3 | 4 | 5 | 6 | 7 | 13 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /model/src/test/java/com/andnexus/test/model/DataTest.java: -------------------------------------------------------------------------------- 1 | package com.andnexus.test.model; 2 | 3 | import com.andnexus.model.Data; 4 | 5 | import org.junit.Test; 6 | import org.junit.runner.RunWith; 7 | import org.junit.runners.Parameterized; 8 | 9 | import java.util.Arrays; 10 | 11 | import static org.junit.Assert.assertEquals; 12 | import static org.junit.runners.Parameterized.Parameters; 13 | 14 | @RunWith(Parameterized.class) 15 | public class DataTest { 16 | 17 | private final Data mData; 18 | 19 | private final String mExpected; 20 | 21 | public DataTest(String expected, Data actual) { 22 | mExpected = expected; 23 | mData = actual; 24 | } 25 | 26 | @Parameters 27 | public static Iterable data() { 28 | return Arrays.asList(new Object[][]{ 29 | {"0", new Data(0)} 30 | }); 31 | } 32 | 33 | @Test 34 | public void shouldCompareOnlyIds() { 35 | assertEquals(mExpected, mData.toString()); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 9 | 10 | 17 | 18 | 19 | 26 | -------------------------------------------------------------------------------- /backend/src/test/java/com/andnexus/backend/ResponseBuilderTest.java: -------------------------------------------------------------------------------- 1 | package com.andnexus.backend; 2 | 3 | import com.andnexus.model.Data; 4 | 5 | import org.junit.Test; 6 | import org.junit.runner.RunWith; 7 | import org.junit.runners.Parameterized; 8 | 9 | import java.util.Arrays; 10 | 11 | import static org.junit.Assert.assertEquals; 12 | 13 | @RunWith(Parameterized.class) 14 | public class ResponseBuilderTest { 15 | 16 | private final Data[] mData; 17 | 18 | private final String mExpected; 19 | 20 | public ResponseBuilderTest(String expected, Data[] data) { 21 | mExpected = expected; 22 | mData = data; 23 | } 24 | 25 | @Parameterized.Parameters 26 | public static Iterable data() { 27 | return Arrays.asList(new Object[][]{ 28 | {"{\"data\":[]}", null,}, 29 | {"{\"data\":[]}", new Data[]{}}, 30 | {"{\"data\":[{\"id\":1}]}", new Data[]{new Data(1)}}, 31 | {"{\"data\":[{\"id\":1},{\"id\":2}]}", new Data[]{new Data(1), new Data(2)}}, 32 | }); 33 | } 34 | 35 | @Test 36 | public void shouldDeliverJsonResponseForData() { 37 | assertEquals(mExpected, new ResponseBuilder().setData(mData).createJson()); 38 | } 39 | } -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: android 2 | env: 3 | global: 4 | - sudo: false 5 | - cache: true 6 | - TERM=dumb # Collect gradle output 7 | 8 | jdk: 9 | - oraclejdk7 10 | 11 | cache: 12 | directories: 13 | - $HOME/.m2 14 | 15 | env: 16 | global: 17 | - TERM=dumb 18 | 19 | before_install: 20 | - chmod +x gradlew 21 | - export TERM=dumb 22 | - ./gradlew -v 23 | - uname -a 24 | 25 | android: 26 | components: 27 | - build-tools-21.1.2 28 | - platform-tools 29 | - tools 30 | - android-21 31 | - extra-google-m2repository 32 | - extra-android-m2repository 33 | licenses: 34 | - 'android-sdk-license-.+' 35 | - 'google-gdk-license-.+' 36 | 37 | notifications: 38 | email: false 39 | 40 | before_script: 41 | - echo no | android create avd --force --name test --target android-19 --abi armeabi-v7a 42 | - emulator -avd test -no-skin -no-audio -no-window & 43 | - android-wait-for-emulator 44 | - adb shell input keyevent 82 & # Disable lock screen 45 | 46 | script: 47 | # Necessary in Container-Based-Infrastructure on Travis CI 48 | - mvn org.apache.maven.plugins:maven-dependency-plugin:2.1:get -DrepoUrl=https://oss.sonatype.org/content/repositories/snapshots -Dartifact=com.google.dagger:dagger:2.0 49 | - ./gradlew connectedAndroidTest -PdisablePreDex 50 | - ./gradlew build -PdisablePreDex 51 | -------------------------------------------------------------------------------- /connect/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'java' 2 | apply plugin: 'jetty' 3 | apply plugin: "jacoco" 4 | 5 | dependencies { 6 | compile project(':model') 7 | compile 'com.google.guava:guava:18.0' 8 | compile 'org.json:json:20140107' 9 | 10 | compile project(':backend') // to start backend on localhost with jetty and test connect integration 11 | 12 | testCompile 'junit:junit:4.10' 13 | testCompile 'org.mockito:mockito-core:1.10.19' 14 | } 15 | 16 | test { 17 | exclude '**/**IntegrationTest**' 18 | } 19 | 20 | task integrationTest(type: Test) { 21 | include '**/**IntegrationTest**' 22 | } 23 | 24 | jettyRun { 25 | logger.info 'Jetty running' 26 | httpPort = new Integer(jettyHttpPort) 27 | scanIntervalSeconds = new Integer(jettyScanIntervalSeconds) 28 | daemon = new Boolean(jettyDaemon) 29 | webAppSourceDirectory = file('../backend/src/main/webapp') 30 | contextPath = '/backend' 31 | } 32 | 33 | jettyRunWar { 34 | logger.info 'Jetty running' 35 | httpPort = new Integer(jettyHttpPort) 36 | daemon = new Boolean(jettyDaemon) 37 | stopKey = 'stopJetty' 38 | stopPort = new Integer(jettyStopPort) 39 | } 40 | 41 | jettyStop { 42 | stopKey = 'Jetty stopping' 43 | stopPort = new Integer(jettyStopPort) 44 | } 45 | 46 | integrationTest.dependsOn jettyRun 47 | integrationTest.finalizedBy jettyStop 48 | test.dependsOn integrationTest 49 | 50 | jacoco { 51 | toolVersion = "0.7.1.201405082137" 52 | reportsDir = file("$buildDir/customJacocoReportDir") 53 | } 54 | 55 | jacocoTestReport { 56 | reports { 57 | xml.enabled false 58 | csv.enabled true 59 | html.destination "${buildDir}/reports/jacoco" 60 | } 61 | } -------------------------------------------------------------------------------- /connect/src/main/java/com/andnexus/connect/Parser.java: -------------------------------------------------------------------------------- 1 | package com.andnexus.connect; 2 | 3 | import com.google.common.base.Charsets; 4 | import com.google.common.io.CharStreams; 5 | 6 | import com.andnexus.model.Data; 7 | 8 | import org.json.JSONArray; 9 | import org.json.JSONObject; 10 | 11 | import java.io.InputStream; 12 | import java.io.InputStreamReader; 13 | import java.util.ArrayList; 14 | import java.util.Collections; 15 | import java.util.List; 16 | 17 | import static com.andnexus.connect.Connect.ConnectException; 18 | import static com.andnexus.connect.Connect.ConnectException.ParserException; 19 | 20 | class Parser { 21 | 22 | List parseArray(JSONArray jsonArray) { 23 | List data = new ArrayList(jsonArray.length()); 24 | for (int i = 0; i < jsonArray.length(); i++) { 25 | final JSONObject jsonObject = jsonArray.optJSONObject(i); 26 | data.add(parseObject(jsonObject)); 27 | } 28 | return data; 29 | } 30 | 31 | Data parseObject(final JSONObject jsonObject) { 32 | return new Data(jsonObject.optInt("id")); 33 | } 34 | 35 | public List getModels(final InputStream inputStream) throws ConnectException { 36 | try { 37 | final String json = CharStreams.toString(new InputStreamReader(inputStream, Charsets.UTF_8)); 38 | List data = Collections.EMPTY_LIST; 39 | if (json.length() > 0) { 40 | JSONArray jsonArray = new JSONObject(json).optJSONArray("data"); 41 | if (jsonArray != null && jsonArray.length() > 0) { 42 | data = parseArray(jsonArray); 43 | } 44 | } 45 | return data; 46 | } catch (Exception e) { 47 | throw new ConnectException(new ParserException(e)); 48 | } 49 | } 50 | 51 | } 52 | -------------------------------------------------------------------------------- /connect/src/main/java/com/andnexus/connect/Connect.java: -------------------------------------------------------------------------------- 1 | package com.andnexus.connect; 2 | 3 | import com.andnexus.model.Data; 4 | 5 | import java.io.IOException; 6 | import java.io.InputStream; 7 | import java.util.List; 8 | 9 | import static com.andnexus.connect.Connect.ConnectException.DeliveryException; 10 | import static com.andnexus.connect.Request.RequestBuilder; 11 | 12 | public class Connect { 13 | 14 | final RequestBuilder mRequestBuilder; 15 | 16 | final Parser mParser; 17 | 18 | public Connect(String url) { 19 | this(new RequestBuilder(url, 8000, "/backend/data"), new Parser()); 20 | } 21 | 22 | Connect(RequestBuilder requestBuilder, Parser parser) { 23 | mRequestBuilder = requestBuilder; 24 | mParser = parser; 25 | } 26 | 27 | public List getData() throws ConnectException { 28 | final InputStream inputStream; 29 | try { 30 | inputStream = mRequestBuilder.create().connect().getInputStream(); 31 | return mParser.getModels(inputStream); 32 | } catch (IOException e) { 33 | throw new ConnectException(new DeliveryException(e)); 34 | } 35 | } 36 | 37 | public static class ConnectException extends Exception { 38 | 39 | public ConnectException(Throwable e) { 40 | super(e); 41 | } 42 | 43 | public static class HostException extends Throwable { 44 | 45 | public HostException(Throwable cause) { 46 | super(cause); 47 | } 48 | } 49 | 50 | public static class ParserException extends Throwable { 51 | 52 | public ParserException(Throwable cause) { 53 | super(cause); 54 | } 55 | } 56 | 57 | public static class RequestException extends Throwable { 58 | 59 | public RequestException(Throwable cause) { 60 | super(cause); 61 | } 62 | } 63 | 64 | public static class DeliveryException extends Throwable { 65 | 66 | public DeliveryException(Throwable cause) { 67 | super(cause); 68 | } 69 | } 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /connect/src/test/java/com/andnexus/connect/ParserTest.java: -------------------------------------------------------------------------------- 1 | package com.andnexus.connect; 2 | 3 | import com.google.common.base.Charsets; 4 | 5 | import com.andnexus.model.Data; 6 | 7 | import junit.framework.Assert; 8 | 9 | import org.json.JSONArray; 10 | import org.json.JSONException; 11 | import org.json.JSONObject; 12 | import org.junit.Before; 13 | import org.junit.Test; 14 | 15 | import java.io.ByteArrayInputStream; 16 | import java.util.Collections; 17 | import java.util.List; 18 | 19 | import static com.andnexus.connect.Connect.ConnectException; 20 | import static com.andnexus.connect.Connect.ConnectException.ParserException; 21 | import static org.junit.Assert.assertEquals; 22 | import static org.junit.Assert.assertTrue; 23 | 24 | 25 | public class ParserTest { 26 | 27 | Parser mParser; 28 | 29 | @Before 30 | public void setUp() throws Exception { 31 | mParser = new Parser(); 32 | } 33 | 34 | @Test 35 | public void shouldReturnData() throws ConnectException { 36 | assertEquals(Collections.EMPTY_LIST, mParser.getModels(new ByteArrayInputStream("".toString().getBytes(Charsets.UTF_8)))); 37 | assertEquals(Collections.EMPTY_LIST, mParser.getModels(new ByteArrayInputStream("{}".toString().getBytes(Charsets.UTF_8)))); 38 | assertEquals(Collections.EMPTY_LIST, mParser.getModels(new ByteArrayInputStream("{data:[]}".toString().getBytes(Charsets.UTF_8)))); 39 | } 40 | 41 | @Test 42 | public void shouldParseObject() throws JSONException { 43 | Data model = mParser.parseObject(new JSONObject("{\"id\":1}")); 44 | assertEquals(1, model.getId()); 45 | } 46 | 47 | @Test 48 | public void shouldParseArray() throws JSONException { 49 | List data = mParser.parseArray(new JSONArray("[{\"id\":1}]")); 50 | assertEquals(1, data.get(0).getId()); 51 | } 52 | 53 | @Test 54 | public void shouldThrowParserException() { 55 | 56 | try { 57 | mParser.getModels(new ByteArrayInputStream("{".toString().getBytes(Charsets.UTF_8))); 58 | Assert.fail("Expected exception."); 59 | } catch (ConnectException exception) { 60 | assertTrue(exception.getCause() instanceof ParserException); 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | apply plugin: 'com.neenbedankt.android-apt' 3 | 4 | android { 5 | compileSdkVersion 21 6 | buildToolsVersion "21.1.2" 7 | 8 | jacoco { 9 | version = '0.6.2.201302030002' 10 | } 11 | 12 | defaultConfig { 13 | applicationId "com.andnexus.android.tests" 14 | minSdkVersion 15 15 | targetSdkVersion 21 16 | versionCode 1 17 | versionName "1.0" 18 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" 19 | } 20 | buildTypes { 21 | debug { 22 | applicationIdSuffix ".debug" 23 | testCoverageEnabled true 24 | } 25 | release { 26 | signingConfig signingConfigs.debug 27 | minifyEnabled false 28 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 29 | } 30 | } 31 | packagingOptions { 32 | exclude 'LICENSE.txt' 33 | } 34 | } 35 | 36 | configurations.all { 37 | resolutionStrategy.cacheChangingModulesFor 0, 'seconds' 38 | } 39 | 40 | dependencies { 41 | 42 | compile project(':connect') 43 | 44 | // Android 45 | compile 'com.android.support:appcompat-v7:21.0.3' 46 | compile 'com.android.support:support-annotations:21.0.3' 47 | compile 'com.jakewharton:butterknife:6.1.0' 48 | 49 | // Dagger 50 | provided 'javax.annotation:javax.annotation-api:1.2' 51 | compile group: "com.google.dagger", name: "dagger", version: "2.0", changing: true 52 | apt group: "com.google.dagger", name: "dagger-compiler", version: "2.0", changing: true 53 | 54 | // Mockito 55 | debugCompile 'com.google.dexmaker:dexmaker-mockito:1.0' 56 | debugCompile 'com.google.dexmaker:dexmaker:1.0' 57 | debugCompile 'org.mockito:mockito-core:1.9.5' 58 | 59 | // Espresso 60 | androidTestCompile('com.android.support.test.espresso:espresso-core:2.0') { 61 | exclude group: 'javax.inject' 62 | } 63 | androidTestCompile 'com.android.support.test:testing-support-lib:0.1' 64 | 65 | // Unit-Tests 66 | // testCompile('junit:junit:4.12') { 67 | // exclude group: 'org.hamcrest', module: 'hamcrest-core' 68 | // } 69 | // releaseCompile 'org.hamcrest:hamcrest-core:+' 70 | } -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 12 | set DEFAULT_JVM_OPTS= 13 | 14 | set DIRNAME=%~dp0 15 | if "%DIRNAME%" == "" set DIRNAME=. 16 | set APP_BASE_NAME=%~n0 17 | set APP_HOME=%DIRNAME% 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windowz variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | if "%@eval[2+2]" == "4" goto 4NT_args 53 | 54 | :win9xME_args 55 | @rem Slurp the command line arguments. 56 | set CMD_LINE_ARGS= 57 | set _SKIP=2 58 | 59 | :win9xME_args_slurp 60 | if "x%~1" == "x" goto execute 61 | 62 | set CMD_LINE_ARGS=%* 63 | goto execute 64 | 65 | :4NT_args 66 | @rem Get arguments from the 4NT Shell from JP Software 67 | set CMD_LINE_ARGS=%$ 68 | 69 | :execute 70 | @rem Setup the command line 71 | 72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if "%ERRORLEVEL%"=="0" goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 85 | exit /b 1 86 | 87 | :mainEnd 88 | if "%OS%"=="Windows_NT" endlocal 89 | 90 | :omega 91 | -------------------------------------------------------------------------------- /connect/src/main/java/com/andnexus/connect/Request.java: -------------------------------------------------------------------------------- 1 | package com.andnexus.connect; 2 | 3 | import java.io.IOException; 4 | import java.net.HttpURLConnection; 5 | import java.net.MalformedURLException; 6 | import java.net.URL; 7 | import java.net.URLStreamHandler; 8 | 9 | import static com.andnexus.connect.Connect.ConnectException; 10 | import static com.andnexus.connect.Connect.ConnectException.HostException; 11 | import static com.andnexus.connect.Connect.ConnectException.RequestException; 12 | import static com.google.common.net.UrlEscapers.urlFormParameterEscaper; 13 | 14 | class Request { 15 | 16 | final URL mUrl; 17 | 18 | Request(URL url) { 19 | mUrl = url; 20 | } 21 | 22 | public HttpURLConnection connect() throws ConnectException { 23 | final long start = System.currentTimeMillis(); 24 | try { 25 | HttpURLConnection connection = (HttpURLConnection) mUrl.openConnection(); 26 | connection.setUseCaches(false); 27 | connection.setDoOutput(false); 28 | connection.connect(); 29 | System.out.println(String.format("Connected with URL %s in %dms.", mUrl, (System.currentTimeMillis() - start) / 1000)); 30 | return connection; 31 | } catch (IOException e) { 32 | throw new ConnectException(new RequestException(e)); 33 | } 34 | } 35 | 36 | public static class RequestBuilder { 37 | 38 | final String mHost; 39 | 40 | final StringBuilder mParameterBuilder; 41 | 42 | final StringBuilder mPathBuilder; 43 | 44 | final int mPort; 45 | 46 | final String mProtocol; 47 | 48 | URLStreamHandler mStreamHandler = null; 49 | 50 | public RequestBuilder(String host, int port, String path) { 51 | this("http", host, port, path); 52 | } 53 | 54 | public RequestBuilder(String protocol, String host, int port, String path) { 55 | mProtocol = protocol; 56 | mHost = host; 57 | mPort = port; 58 | mPathBuilder = new StringBuilder(path); 59 | mParameterBuilder = new StringBuilder(); 60 | } 61 | 62 | final static String getParameterPrefix(StringBuilder stringBuilder) { 63 | return stringBuilder.length() == 0 ? "?" : "&"; 64 | } 65 | 66 | /** 67 | * Specifying a handler of null, which is default, indicates that the URL should use a default stream handler. 68 | */ 69 | public RequestBuilder setStreamHandler(URLStreamHandler streamHandler) { 70 | mStreamHandler = streamHandler; 71 | return this; 72 | } 73 | 74 | public RequestBuilder addParameter(String key, String value) { 75 | mParameterBuilder.append(String.format("%s%s=%s", getParameterPrefix(mParameterBuilder), key, urlFormParameterEscaper().escape(value))); 76 | return this; 77 | } 78 | 79 | public RequestBuilder appendPath(String path) { 80 | mPathBuilder.append(path); 81 | return this; 82 | } 83 | 84 | protected Request create() throws ConnectException { 85 | try { 86 | return new Request(new URL(mProtocol, mHost, mPort, mPathBuilder.toString() + mParameterBuilder.toString(), mStreamHandler)); 87 | } catch (MalformedURLException e) { 88 | throw new ConnectException(new HostException(e)); 89 | } 90 | } 91 | } 92 | 93 | } -------------------------------------------------------------------------------- /app/src/debug/java/com/andnexus/android/tests/ActivityTest.java: -------------------------------------------------------------------------------- 1 | package com.andnexus.android.tests; 2 | 3 | import com.andnexus.connect.Connect; 4 | 5 | import org.mockito.Mock; 6 | import org.mockito.MockitoAnnotations; 7 | 8 | import android.app.Activity; 9 | import android.app.KeyguardManager; 10 | import android.net.ConnectivityManager; 11 | import android.net.NetworkInfo; 12 | import android.os.PowerManager; 13 | import android.test.ActivityInstrumentationTestCase2; 14 | 15 | import javax.inject.Inject; 16 | import javax.inject.Singleton; 17 | 18 | import dagger.Provides; 19 | 20 | import static android.content.Context.KEYGUARD_SERVICE; 21 | import static android.content.Context.POWER_SERVICE; 22 | import static android.os.PowerManager.ACQUIRE_CAUSES_WAKEUP; 23 | import static android.os.PowerManager.FULL_WAKE_LOCK; 24 | import static android.os.PowerManager.ON_AFTER_RELEASE; 25 | import static android.view.WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED; 26 | import static com.andnexus.android.tests.MainActivity.OnCreateListener; 27 | import static org.mockito.Mockito.when; 28 | 29 | public abstract class ActivityTest extends ActivityInstrumentationTestCase2 { 30 | 31 | @Inject 32 | ConnectivityManager mConnectivityManager; 33 | 34 | @Inject 35 | Connect mConnect; 36 | 37 | public ActivityTest() { 38 | super(MainActivity.class); 39 | } 40 | 41 | @Override 42 | protected void setUp() throws Exception { 43 | super.setUp(); 44 | 45 | App app = (App) getInstrumentation().getTargetContext().getApplicationContext(); 46 | app.graph().inject(this); 47 | } 48 | 49 | @dagger.Module 50 | public static final class Module { 51 | 52 | @Mock 53 | ConnectivityManager mConnectivityManager; 54 | 55 | @Mock 56 | NetworkInfo mNetworkInfo; 57 | 58 | @Mock 59 | Connect mConnect; 60 | 61 | public Module() { 62 | MockitoAnnotations.initMocks(this); 63 | } 64 | 65 | @Provides 66 | @Singleton 67 | public ConnectivityManager provideConnectivityManager() { 68 | when(mConnectivityManager.getActiveNetworkInfo()).thenReturn(mNetworkInfo); 69 | return mConnectivityManager; 70 | } 71 | 72 | @Provides 73 | @Singleton 74 | public Connect provideConnect() { 75 | return mConnect; 76 | } 77 | 78 | @Provides 79 | @Singleton 80 | public OnCreateListener provideOnCreateListener() { 81 | return new OnCreateListener() { 82 | @Override 83 | public void onCreate(Activity activity) { 84 | 85 | // http://developer.android.com/tools/testing/activity_testing.html#UnlockDevice 86 | KeyguardManager keyguardManager = (KeyguardManager) activity.getSystemService(KEYGUARD_SERVICE); 87 | KeyguardManager.KeyguardLock lock = keyguardManager.newKeyguardLock(MainActivity.class.getSimpleName()); 88 | lock.disableKeyguard(); 89 | 90 | // https://gist.github.com/JakeWharton/f50f3b4d87e57d8e96e9 91 | activity.getWindow().addFlags(FLAG_SHOW_WHEN_LOCKED); 92 | PowerManager power = (PowerManager) activity.getSystemService(POWER_SERVICE); 93 | PowerManager.WakeLock wakeLock = power.newWakeLock(FULL_WAKE_LOCK | ACQUIRE_CAUSES_WAKEUP | ON_AFTER_RELEASE, "wakeup!"); 94 | wakeLock.acquire(); 95 | wakeLock.release(); 96 | } 97 | }; 98 | } 99 | 100 | } 101 | } -------------------------------------------------------------------------------- /connect/src/test/java/com/andnexus/connect/RequestTest.java: -------------------------------------------------------------------------------- 1 | package com.andnexus.connect; 2 | 3 | import com.google.common.base.Charsets; 4 | import com.google.common.io.CharStreams; 5 | 6 | import junit.framework.Assert; 7 | 8 | import org.junit.Before; 9 | import org.junit.Test; 10 | import org.mockito.Mock; 11 | import org.mockito.MockitoAnnotations; 12 | 13 | import java.io.ByteArrayInputStream; 14 | import java.io.IOException; 15 | import java.io.InputStreamReader; 16 | import java.net.HttpURLConnection; 17 | import java.net.URL; 18 | import java.net.URLConnection; 19 | import java.net.URLStreamHandler; 20 | 21 | import static com.andnexus.connect.Connect.ConnectException; 22 | import static org.junit.Assert.assertEquals; 23 | import static org.junit.Assert.assertTrue; 24 | import static org.mockito.Mockito.when; 25 | 26 | public class RequestTest { 27 | 28 | @Mock 29 | HttpURLConnection mHttpURLConnection; 30 | 31 | @Before 32 | public void setUp() throws Exception { 33 | 34 | MockitoAnnotations.initMocks(this); 35 | } 36 | 37 | @Test 38 | public void shouldTest() { 39 | assertEquals("?", Request.RequestBuilder.getParameterPrefix(new StringBuilder())); 40 | assertEquals("&", Request.RequestBuilder.getParameterPrefix(new StringBuilder("?name=value"))); 41 | } 42 | 43 | @Test 44 | public void shouldBuildRequest() throws ConnectException { 45 | 46 | // Prepare 47 | Request request = new Request.RequestBuilder("example.com", 80, "/data") 48 | .addParameter("param", "?& ") 49 | .appendPath("/test") 50 | .create(); 51 | 52 | // Pre execution test 53 | assertEquals("example.com", request.mUrl.getHost()); 54 | assertEquals("/data/test", request.mUrl.getPath()); 55 | assertEquals("param=%3F%26+", request.mUrl.getQuery()); 56 | } 57 | 58 | @Test 59 | public void shouldDispatchRequest() throws ConnectException, IOException { 60 | 61 | // Prepare 62 | Request request = new Request.RequestBuilder("host", 80, "/path") 63 | .setStreamHandler(new URLStreamHandler() { 64 | @Override 65 | protected URLConnection openConnection(final URL url) throws IOException { 66 | when(mHttpURLConnection.getInputStream()).thenReturn(new ByteArrayInputStream("{}".getBytes(Charsets.UTF_8))); 67 | return mHttpURLConnection; 68 | } 69 | }) 70 | .create(); 71 | HttpURLConnection connection = request.connect(); 72 | 73 | // Post execution test 74 | assertEquals("{}", CharStreams.toString(new InputStreamReader(connection.getInputStream(), Charsets.UTF_8))); 75 | } 76 | 77 | @Test 78 | public void shouldThrowHostException() { 79 | 80 | try { 81 | new Request.RequestBuilder("", "host", 80, "/path").create(); 82 | Assert.fail("Expected exception."); 83 | } catch (ConnectException exception) { 84 | assertTrue(exception.getCause() instanceof ConnectException.HostException); 85 | } 86 | } 87 | 88 | @Test 89 | public void shouldThrowRequestException() throws ConnectException, IOException { 90 | 91 | // Prepare 92 | Request request = new Request.RequestBuilder("host", 80, "/path") 93 | .setStreamHandler(new URLStreamHandler() { 94 | @Override 95 | protected URLConnection openConnection(final URL url) throws IOException { 96 | throw new IOException(); 97 | } 98 | }) 99 | .create(); 100 | try { 101 | request.connect(); 102 | Assert.fail("Expected exception."); 103 | } catch (ConnectException exception) { 104 | assertTrue(exception.getCause() instanceof ConnectException.RequestException); 105 | } 106 | } 107 | } 108 | -------------------------------------------------------------------------------- /connect/src/test/java/com/andnexus/connect/ConnectTest.java: -------------------------------------------------------------------------------- 1 | package com.andnexus.connect; 2 | 3 | import junit.framework.Assert; 4 | 5 | import org.junit.Before; 6 | import org.junit.Test; 7 | import org.mockito.Mock; 8 | import org.mockito.MockitoAnnotations; 9 | import org.mockito.invocation.InvocationOnMock; 10 | import org.mockito.stubbing.Answer; 11 | 12 | import java.io.IOException; 13 | import java.io.InputStream; 14 | import java.net.HttpURLConnection; 15 | import java.net.URL; 16 | import java.net.URLConnection; 17 | import java.net.URLStreamHandler; 18 | import java.util.Collections; 19 | 20 | import static com.andnexus.connect.Connect.ConnectException; 21 | import static com.andnexus.connect.Connect.ConnectException.DeliveryException; 22 | import static com.andnexus.connect.Request.RequestBuilder; 23 | import static org.junit.Assert.assertEquals; 24 | import static org.junit.Assert.assertTrue; 25 | import static org.mockito.Mockito.times; 26 | import static org.mockito.Mockito.verify; 27 | import static org.mockito.Mockito.when; 28 | 29 | public class ConnectTest { 30 | 31 | @Mock 32 | Parser mParser; 33 | 34 | @Mock 35 | Request mRequest; 36 | 37 | @Mock 38 | RequestBuilder mRequestBuilder; 39 | 40 | @Mock 41 | HttpURLConnection mConnection; 42 | 43 | @Mock 44 | InputStream mInputStream; 45 | 46 | @Before 47 | public void setUp() throws Exception { 48 | 49 | MockitoAnnotations.initMocks(this); 50 | when(mConnection.getInputStream()).thenReturn(mInputStream); 51 | when(mRequest.connect()).thenReturn(mConnection); 52 | when(mRequestBuilder.create()).thenReturn(mRequest); 53 | } 54 | 55 | @Test 56 | public void shouldReturnEmptyList() throws ConnectException { 57 | 58 | assertEquals(Collections.EMPTY_LIST, new Connect(mRequestBuilder, mParser).getData()); 59 | } 60 | 61 | @Test 62 | public void shouldIntegrateParser() throws ConnectException { 63 | 64 | Connect connect = new Connect(mRequestBuilder, mParser); 65 | 66 | connect.getData(); 67 | verify(mParser, times(1)).getModels(mInputStream); 68 | } 69 | 70 | @Test 71 | public void shouldExecuteRequest() throws ConnectException { 72 | 73 | Connect connect = new Connect(mRequestBuilder, mParser); 74 | connect.getData(); 75 | verify(mRequest, times(1)).connect(); 76 | } 77 | 78 | @Test 79 | public void shouldSetupWithDefaultRequestBuilderAndParser() { 80 | 81 | Connect connect = new Connect("localhost"); 82 | assertEquals("localhost", connect.mRequestBuilder.mHost); 83 | assertEquals("/backend/data", connect.mRequestBuilder.mPathBuilder.toString()); 84 | } 85 | 86 | @Test 87 | public void shouldThrowDeliveryException() throws ConnectException { 88 | 89 | // Prepare 90 | Connect connect = new Connect(new Request.RequestBuilder("host", 80, "/path") 91 | .setStreamHandler(new URLStreamHandler() { 92 | @Override 93 | protected URLConnection openConnection(final URL url) throws IOException { 94 | when(mConnection.getInputStream()).then(new Answer() { 95 | @Override 96 | public Object answer(InvocationOnMock invocation) throws Throwable { 97 | throw new IOException(); 98 | } 99 | }); 100 | return mConnection; 101 | } 102 | 103 | }), mParser); 104 | 105 | // Test 106 | try { 107 | connect.getData(); 108 | Assert.fail("Expected exception."); 109 | } catch (ConnectException exception) { 110 | assertTrue(exception.getCause() instanceof DeliveryException); 111 | } finally { 112 | 113 | // Reset 114 | when(mRequest.connect()).thenReturn(mConnection); 115 | } 116 | } 117 | } 118 | -------------------------------------------------------------------------------- /app/src/androidTest/java/com/andnexus/android/tests/MainActivityTest.java: -------------------------------------------------------------------------------- 1 | package com.andnexus.android.tests; 2 | 3 | import com.andnexus.model.Data; 4 | 5 | import android.os.AsyncTask; 6 | import android.support.annotation.IdRes; 7 | import android.support.test.espresso.Espresso; 8 | import android.test.suitebuilder.annotation.LargeTest; 9 | 10 | import java.util.ArrayList; 11 | import java.util.Arrays; 12 | import java.util.Collections; 13 | import java.util.List; 14 | 15 | import static android.support.test.espresso.Espresso.onView; 16 | import static android.support.test.espresso.action.ViewActions.click; 17 | import static android.support.test.espresso.assertion.ViewAssertions.matches; 18 | import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed; 19 | import static android.support.test.espresso.matcher.ViewMatchers.withId; 20 | import static android.support.test.espresso.matcher.ViewMatchers.withText; 21 | import static com.andnexus.connect.Connect.ConnectException; 22 | import static org.hamcrest.Matchers.allOf; 23 | import static org.hamcrest.Matchers.instanceOf; 24 | import static org.hamcrest.core.Is.is; 25 | import static org.mockito.Mockito.mock; 26 | import static org.mockito.Mockito.when; 27 | 28 | @LargeTest 29 | public class MainActivityTest extends ActivityTest { 30 | 31 | MainActivity mActivity; 32 | 33 | @Override 34 | public void setUp() throws Exception { 35 | super.setUp(); 36 | 37 | mActivity = getActivity(); 38 | } 39 | 40 | private void refresh() { 41 | onView(withId(R.id.action_refresh)) 42 | .perform(click()); 43 | } 44 | 45 | public void testShouldDisplayOfflineHint() throws Throwable { 46 | 47 | // Prepare 48 | when(mConnect.getData()).thenReturn(Collections.EMPTY_LIST); 49 | when(mConnectivityManager.getActiveNetworkInfo().isConnected()).thenReturn(false); 50 | 51 | // Test 52 | refresh(); 53 | 54 | onView(withText(mActivity.getString(R.string.offline))) 55 | .check(matches(isDisplayed())); 56 | } 57 | 58 | public void testShouldDisplayOfflineHintAfterSuccessfullyLoadedData() throws ConnectException { 59 | 60 | // Prepare 61 | when(mConnect.getData()).thenReturn(Arrays.asList(new Data[]{new Data(1)})); 62 | when(mConnectivityManager.getActiveNetworkInfo().isConnected()).thenReturn(true); 63 | 64 | // Test 65 | refresh(); 66 | 67 | when(mConnect.getData()).thenReturn(Collections.EMPTY_LIST); 68 | when(mConnectivityManager.getActiveNetworkInfo().isConnected()).thenReturn(false); 69 | 70 | refresh(); 71 | 72 | onView(withText(mActivity.getString(R.string.offline))) 73 | .check(matches(isDisplayed())); 74 | 75 | } 76 | 77 | public void testShouldDisplayNoDataHint() throws ConnectException { 78 | 79 | // Prepare 80 | when(mConnect.getData()).thenReturn(Collections.EMPTY_LIST); 81 | when(mConnectivityManager.getActiveNetworkInfo().isConnected()).thenReturn(true); 82 | 83 | // Test 84 | refresh(); 85 | 86 | onView(withText(mActivity.getString(R.string.empty))) 87 | .check(matches(isDisplayed())); 88 | } 89 | 90 | public void testShouldDisplayData() throws ConnectException { 91 | 92 | // Prepare 93 | List data = new ArrayList(); 94 | for (int i = 0; i < 100; i++) { 95 | data.add(new Data(i)); 96 | } 97 | when(mConnect.getData()).thenReturn(data); 98 | when(mConnectivityManager.getActiveNetworkInfo().isConnected()).thenReturn(true); 99 | 100 | // Test 101 | refresh(); 102 | 103 | onData(R.id.list, 99, "99"); 104 | } 105 | 106 | public void testShouldNotExecuteTaskIfIsRunning() throws ConnectException { 107 | 108 | when(mConnectivityManager.getActiveNetworkInfo().isConnected()).thenReturn(true); 109 | 110 | // Should refresh 111 | when(mConnect.getData()).thenReturn(Arrays.asList(new Data[]{new Data(1)})); 112 | mActivity.mTask = null; 113 | 114 | refresh(); 115 | onData(R.id.list, 0, "1"); 116 | 117 | // Should not refresh 118 | when(mConnect.getData()).thenReturn(Arrays.asList(new Data[]{new Data(2)})); 119 | mActivity.mTask = mock(AsyncTask.class); 120 | 121 | refresh(); 122 | onData(R.id.list, 0, "1"); 123 | } 124 | 125 | void onData(@IdRes int res, int position, String expected) { 126 | Espresso.onData(allOf(is(instanceOf(Data.class)))) 127 | .inAdapterView(withId(res)) 128 | .atPosition(position) 129 | .check(matches(withText(expected))); 130 | } 131 | } 132 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Automatische Tests für Android 2 | 3 | 4 | Der Prozess der Qualitätssicherung von Software wird unter anderem durch automatische Testverfahren greifbar. Mit [Dagger](http://google.github.com/dagger), [Mockito](https://code.google.com/p/mockito/) und [Espresso](https://code.google.com/p/android-test-kit) lassen sich Tests für Android entwerfen, die die manuellen Testaufwände drastisch reduzieren können. 5 | 6 | [![Build Status](https://travis-ci.org/andnexus/android-testing.svg?branch=master)](https://travis-ci.org/andnexus/android-testing) 7 | 8 | # Praktisches Beispiel 9 | 10 | Eine Webanwendung soll Daten über eine Schnittstelle an eine App ausliefern. 11 | 12 | ## Backend 13 | 14 | Die Webanwendung nach der Java-Servlet-Spezifikation liefert unter dem Pfad ```/backend/data``` das JSON Objekt ```{data:[{"id":123},{"id":456}]}``` aus. 15 | 16 | ## Model 17 | 18 | Das Datenmodell bildet die JSON Struktur in einer Klasse ab. 19 | 20 | ## Connect 21 | 22 | Liefert die Datenmodelle aus der Webanwendung an die App aus. 23 | 24 | ## App 25 | 26 | Android App Komponenten. 27 | 28 | ## Web 29 | 30 | Diese Softwarearchitektur lässt zu, dass mit dem [Google Web Toolkit](http://www.gwtproject.org) die Module Model und Connect in JavaScript übersetzt werden können. 31 | 32 | ## iOS 33 | 34 | Mittels [J2ObjC](https://github.com/google/j2objc) können die Module Model und Connect automatisch auf iOS portiert werden. 35 | 36 | # Testplan 37 | 38 | ## Modultests 39 | 40 | Die Java Module Model, Connect und Backend werden mit JUnit4 und unter Einsatz von Mockito getestet. 41 | 42 | ./gradlew test 43 | 44 | ![Screenshot](assets/java-connect-tests.png "Tests") 45 | 46 | Mittels Jacoco lässt sich beim Java Modul Connect eine Testabdeckung von 100% nachweisen. 47 | 48 | ./gradlew jacocoTestReport 49 | 50 | ![Screenshot](assets/java-connect-jacoco.png "Code coverage") 51 | 52 | ## Android 53 | 54 | In der Activity wird z.B. der ConnectivityManager mittels Dagger Dependency Injection bereitgestellt. 55 | 56 | ``` 57 | private boolean isOffline() { 58 | 59 | final NetworkInfo activeNetworkInfo = mConnectivityManager.getActiveNetworkInfo(); 60 | return activeNetworkInfo == null || !activeNetworkInfo.isConnected(); 61 | } 62 | ``` 63 | 64 | Der UI Test mit Espresso ermöglicht das gewünschte Verhalten der App während der unterschiedlichen Verbindungszustände nachzuweisen. 65 | 66 | ``` 67 | public void testShouldDisplayOfflineHint() { 68 | 69 | when(mConnectivityManager.getActiveNetworkInfo().isConnected()).thenReturn(false); 70 | 71 | onView(withId(R.id.refresh)) 72 | .perform(swipeDown()); 73 | 74 | onView(withText(mActivity.getString(R.string.offline))) 75 | .check(matches(isDisplayed())); 76 | } 77 | ``` 78 | 79 | Die Android Komponenten werden mit plattformeigenen testing APIs, Espresso und JUnit3 getestet. 80 | 81 | ./gradlew connectedCheck 82 | 83 | ![Screenshot](assets/android-testing.gif "UI Tests") 84 | 85 | ## Integrationstests 86 | 87 | Im Connect-Modul sind für den Gradle Task ```integrationTest``` Tests hinterlegt. Dabei wird zu beginn das Backend gebaut und ist anschließend unter ```http://localhost:8000``` erreichbar. Damit der Task nicht blockiert wird muss folgende Einstellung gesetzt sein. 88 | 89 | org.gradle.daemon=false 90 | 91 | Mit dem starten des Tasks ```test``` wird automatisch auch der Task ```integrationTest``` angestoßen. 92 | 93 | Nach Änderungen am Quellcode werden die Variationen der App, das Connect-Modul und das Backend automatisch [gebaut, gestartet und getestet](https://travis-ci.org/andnexus/android-testing). 94 | 95 | ## Manuelle Tests 96 | 97 | Ein Variant besteht aus Product-Flavor und Build-Type. Variants mit Build-Type Debug sind ausschließlich für automatische Tests vorgesehen. Build-Types vom Typ Release erwarten eine Instanz des Backends hinter der URL oder IP der folgenden Android-Ressource. 98 | 99 | INSERT_YOUR_URI 100 | 101 | Ein einfacher Weg ist die folgende Einstellung sicherzustellen 102 | 103 | org.gradle.daemon=true 104 | 105 | und mit 106 | 107 | ./gradlew jettyRun 108 | 109 | eine Backend-Instanz zu starten. Dieser Task läuft bis man ihn in der Konsole beendet und lässt manuelle Test in der App zu. Alternativ kann man auch ein Web Application Archive bauen und auf einen Server laden. 110 | 111 | # Continuous Delivery 112 | 113 | Der letze Schritt ist die Apps zu verteilen. Die [Google Play Publisher API](https://developers.google.com/android-publisher) erlaubt hier automisch Build-Artefakte auf den Stages Alpha, Beta und Production zu platzieren. Damit lassen sich Apps an ausgewählte Tester oder alle Play Store Benutzer verteilen. [Mehr Erfahren...](http://www.andnexus.com) 114 | 115 | License 116 | ------- 117 | 118 | Licensed to the Apache Software Foundation (ASF) under one or more contributor 119 | license agreements. See the NOTICE file distributed with this work for 120 | additional information regarding copyright ownership. The ASF licenses this 121 | file to you under the Apache License, Version 2.0 (the "License"); you may not 122 | use this file except in compliance with the License. You may obtain a copy of 123 | the License at 124 | 125 | http://www.apache.org/licenses/LICENSE-2.0 126 | 127 | Unless required by applicable law or agreed to in writing, software 128 | distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 129 | WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 130 | License for the specific language governing permissions and limitations under 131 | the License. 132 | 133 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 10 | DEFAULT_JVM_OPTS="" 11 | 12 | APP_NAME="Gradle" 13 | APP_BASE_NAME=`basename "$0"` 14 | 15 | # Use the maximum available, or set MAX_FD != -1 to use that value. 16 | MAX_FD="maximum" 17 | 18 | warn ( ) { 19 | echo "$*" 20 | } 21 | 22 | die ( ) { 23 | echo 24 | echo "$*" 25 | echo 26 | exit 1 27 | } 28 | 29 | # OS specific support (must be 'true' or 'false'). 30 | cygwin=false 31 | msys=false 32 | darwin=false 33 | case "`uname`" in 34 | CYGWIN* ) 35 | cygwin=true 36 | ;; 37 | Darwin* ) 38 | darwin=true 39 | ;; 40 | MINGW* ) 41 | msys=true 42 | ;; 43 | esac 44 | 45 | # For Cygwin, ensure paths are in UNIX format before anything is touched. 46 | if $cygwin ; then 47 | [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 48 | fi 49 | 50 | # Attempt to set APP_HOME 51 | # Resolve links: $0 may be a link 52 | PRG="$0" 53 | # Need this for relative symlinks. 54 | while [ -h "$PRG" ] ; do 55 | ls=`ls -ld "$PRG"` 56 | link=`expr "$ls" : '.*-> \(.*\)$'` 57 | if expr "$link" : '/.*' > /dev/null; then 58 | PRG="$link" 59 | else 60 | PRG=`dirname "$PRG"`"/$link" 61 | fi 62 | done 63 | SAVED="`pwd`" 64 | cd "`dirname \"$PRG\"`/" >&- 65 | APP_HOME="`pwd -P`" 66 | cd "$SAVED" >&- 67 | 68 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 69 | 70 | # Determine the Java command to use to start the JVM. 71 | if [ -n "$JAVA_HOME" ] ; then 72 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 73 | # IBM's JDK on AIX uses strange locations for the executables 74 | JAVACMD="$JAVA_HOME/jre/sh/java" 75 | else 76 | JAVACMD="$JAVA_HOME/bin/java" 77 | fi 78 | if [ ! -x "$JAVACMD" ] ; then 79 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 80 | 81 | Please set the JAVA_HOME variable in your environment to match the 82 | location of your Java installation." 83 | fi 84 | else 85 | JAVACMD="java" 86 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 87 | 88 | Please set the JAVA_HOME variable in your environment to match the 89 | location of your Java installation." 90 | fi 91 | 92 | # Increase the maximum file descriptors if we can. 93 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then 94 | MAX_FD_LIMIT=`ulimit -H -n` 95 | if [ $? -eq 0 ] ; then 96 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 97 | MAX_FD="$MAX_FD_LIMIT" 98 | fi 99 | ulimit -n $MAX_FD 100 | if [ $? -ne 0 ] ; then 101 | warn "Could not set maximum file descriptor limit: $MAX_FD" 102 | fi 103 | else 104 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 105 | fi 106 | fi 107 | 108 | # For Darwin, add options to specify how the application appears in the dock 109 | if $darwin; then 110 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 111 | fi 112 | 113 | # For Cygwin, switch paths to Windows format before running java 114 | if $cygwin ; then 115 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 116 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules 158 | function splitJvmOpts() { 159 | JVM_OPTS=("$@") 160 | } 161 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS 162 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" 163 | 164 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" 165 | -------------------------------------------------------------------------------- /app/src/main/java/com/andnexus/android/tests/MainActivity.java: -------------------------------------------------------------------------------- 1 | package com.andnexus.android.tests; 2 | 3 | import com.andnexus.connect.Connect; 4 | import com.andnexus.model.Data; 5 | 6 | import android.app.Activity; 7 | import android.content.Context; 8 | import android.net.ConnectivityManager; 9 | import android.net.NetworkInfo; 10 | import android.os.AsyncTask; 11 | import android.os.Bundle; 12 | import android.support.v4.widget.SwipeRefreshLayout; 13 | import android.support.v7.app.ActionBarActivity; 14 | import android.util.Log; 15 | import android.view.Menu; 16 | import android.view.MenuItem; 17 | import android.widget.ArrayAdapter; 18 | import android.widget.ListView; 19 | import android.widget.TextView; 20 | 21 | import java.util.ArrayList; 22 | import java.util.Collections; 23 | import java.util.List; 24 | 25 | import javax.inject.Inject; 26 | import javax.inject.Singleton; 27 | 28 | import butterknife.ButterKnife; 29 | import butterknife.InjectView; 30 | import dagger.Provides; 31 | 32 | import static com.andnexus.connect.Connect.ConnectException; 33 | 34 | public class MainActivity extends ActionBarActivity implements SwipeRefreshLayout.OnRefreshListener { 35 | 36 | @Inject 37 | ConnectivityManager mConnectivityManager; 38 | 39 | @Inject 40 | Connect mConnect; 41 | 42 | @Inject 43 | OnCreateListener mOnCreateListener; 44 | 45 | @InjectView(R.id.refresh) 46 | SwipeRefreshLayout mRefreshView; 47 | 48 | @InjectView(R.id.empty) 49 | TextView mEmptyView; 50 | 51 | @InjectView(R.id.list) 52 | ListView mListView; 53 | 54 | ArrayAdapter mAdapter; 55 | 56 | List mData = new ArrayList(); 57 | 58 | AsyncTask> mTask; 59 | 60 | @Override 61 | protected void onCreate(Bundle savedInstanceState) { 62 | super.onCreate(savedInstanceState); 63 | 64 | ((App) getApplication()).graph().inject(this); 65 | 66 | mOnCreateListener.onCreate(this); 67 | 68 | setContentView(R.layout.activity_main); 69 | ButterKnife.inject(this); 70 | 71 | onCreateListView(); 72 | onCreateRefreshView(); 73 | 74 | onRefresh(); 75 | } 76 | 77 | private void onCreateListView() { 78 | mListView.setEmptyView(mEmptyView); 79 | mAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, mData); 80 | mListView.setAdapter(mAdapter); 81 | } 82 | 83 | private void onCreateRefreshView() { 84 | mRefreshView.setOnRefreshListener(this); 85 | mRefreshView.setRefreshing(true); 86 | } 87 | 88 | @Override 89 | public boolean onCreateOptionsMenu(Menu menu) { 90 | getMenuInflater().inflate(R.menu.main, menu); 91 | return super.onCreateOptionsMenu(menu); 92 | } 93 | 94 | @Override 95 | public boolean onOptionsItemSelected(MenuItem item) { 96 | if (item.getItemId() == R.id.action_refresh) { 97 | onRefresh(); 98 | } 99 | return super.onOptionsItemSelected(item); 100 | } 101 | 102 | @Override 103 | public void onRefresh() { 104 | if (mTask == null) { 105 | mTask = new AsyncTask>() { 106 | 107 | @Override 108 | protected void onPreExecute() { 109 | super.onPreExecute(); 110 | mData.clear(); 111 | mAdapter.notifyDataSetChanged(); 112 | mEmptyView.setText(null); 113 | } 114 | 115 | @Override 116 | protected List doInBackground(Void... params) { 117 | List data = Collections.EMPTY_LIST; 118 | try { 119 | data = mConnect.getData(); 120 | } catch (ConnectException e) { 121 | Log.e("Connect", e.getMessage(), e); 122 | } 123 | return data; 124 | } 125 | 126 | @Override 127 | protected void onPostExecute(List data) { 128 | super.onPostExecute(data); 129 | if (data.size() == 0) { 130 | if (isOffline()) { 131 | mEmptyView.setText(R.string.offline); 132 | } else { 133 | mEmptyView.setText(R.string.empty); 134 | } 135 | } else { 136 | mData.addAll(data); 137 | mAdapter.notifyDataSetChanged(); 138 | } 139 | mRefreshView.setRefreshing(false); 140 | mTask = null; 141 | } 142 | }.execute(); 143 | } 144 | } 145 | 146 | private boolean isOffline() { 147 | final NetworkInfo activeNetworkInfo = mConnectivityManager.getActiveNetworkInfo(); 148 | return activeNetworkInfo == null || !activeNetworkInfo.isConnected(); 149 | } 150 | 151 | public interface OnCreateListener { 152 | 153 | void onCreate(Activity activity); 154 | } 155 | 156 | @dagger.Module 157 | public final static class Module { 158 | 159 | private final Context mContext; 160 | 161 | public Module(Context context) { 162 | mContext = context; 163 | } 164 | 165 | @Provides 166 | @Singleton 167 | public ConnectivityManager provideConnectivityManager() { 168 | return (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE); 169 | } 170 | 171 | @Provides 172 | @Singleton 173 | public Connect provideConnect() { 174 | return new Connect(mContext.getString(R.string.url_backend)); 175 | } 176 | 177 | @Provides 178 | @Singleton 179 | public OnCreateListener provideOnCreateListener() { 180 | return new OnCreateListener() { 181 | @Override 182 | public void onCreate(Activity activity) { 183 | 184 | } 185 | }; 186 | } 187 | } 188 | } 189 | -------------------------------------------------------------------------------- /assets/LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2014 The Android Open Source Project 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------