├── .gitignore ├── README.md ├── app ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ ├── main │ ├── AndroidManifest.xml │ ├── java │ │ └── it │ │ │ └── codingjam │ │ │ └── testingrxjava │ │ │ ├── MainActivity.java │ │ │ ├── MainActivity1.java │ │ │ ├── UserStats.java │ │ │ ├── gson │ │ │ ├── Badge.java │ │ │ ├── BadgeResponse.java │ │ │ ├── MyAdapterFactory.java │ │ │ ├── User.java │ │ │ └── UserResponse.java │ │ │ ├── rxjava1 │ │ │ ├── StackOverflowService.java │ │ │ ├── StackOverflowServiceFactory.java │ │ │ ├── UserService.java │ │ │ ├── UserService2.java │ │ │ └── UserService3.java │ │ │ └── rxjava2 │ │ │ ├── StackOverflowService.java │ │ │ ├── StackOverflowServiceFactory.java │ │ │ ├── UserService.java │ │ │ ├── UserService2.java │ │ │ └── UserService3.java │ └── res │ │ ├── layout │ │ └── activity_main.xml │ │ ├── mipmap-hdpi │ │ └── ic_launcher.png │ │ ├── mipmap-mdpi │ │ └── ic_launcher.png │ │ ├── mipmap-xhdpi │ │ └── ic_launcher.png │ │ ├── mipmap-xxhdpi │ │ └── ic_launcher.png │ │ ├── mipmap-xxxhdpi │ │ └── ic_launcher.png │ │ ├── values-w820dp │ │ └── dimens.xml │ │ └── values │ │ ├── colors.xml │ │ ├── dimens.xml │ │ ├── strings.xml │ │ └── styles.xml │ └── test │ └── java │ ├── it │ └── codingjam │ │ └── testingrxjava │ │ ├── ConditionUtils.java │ │ ├── ExampleUnitTest.java │ │ ├── ImmediateSchedulerRule.java │ │ ├── PredicateUtils.java │ │ ├── TestSchedulerRule.java │ │ ├── TestSchedulerRule1.java │ │ ├── rxjava1 │ │ ├── UserServiceTest_1.java │ │ ├── UserServiceTest_2.java │ │ ├── UserServiceTest_3.java │ │ ├── UserServiceTest_4.java │ │ ├── UserServiceTest_5.java │ │ ├── UserServiceTest_6.java │ │ ├── UserServiceTest_7.java │ │ └── UserServiceTest_8.java │ │ └── rxjava2 │ │ ├── UserServiceTest_1.java │ │ ├── UserServiceTest_2.java │ │ ├── UserServiceTest_3.java │ │ ├── UserServiceTest_4.java │ │ ├── UserServiceTest_5.java │ │ ├── UserServiceTest_6.java │ │ ├── UserServiceTest_7.java │ │ └── UserServiceTest_8.java │ └── org │ └── mockito │ └── configuration │ └── MockitoConfiguration.java ├── build.gradle ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .gradle 3 | /local.properties 4 | /.idea/* 5 | .DS_Store 6 | /build 7 | /captures 8 | .externalNativeBuild 9 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # TestingRxJavaUsingMockito 2 | Demo project for the post [Testing asynchronous RxJava code using Mockito](https://medium.com/@fabioCollini/testing-asynchronous-rxjava-code-using-mockito-8ad831a16877) 3 | -------------------------------------------------------------------------------- /app/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | apply plugin: 'me.tatarka.retrolambda' 4 | 5 | android { 6 | compileSdkVersion 25 7 | buildToolsVersion "24.0.2" 8 | defaultConfig { 9 | applicationId "it.codingjam.testingrxjava" 10 | minSdkVersion 15 11 | targetSdkVersion 25 12 | versionCode 1 13 | versionName "1.0" 14 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" 15 | } 16 | buildTypes { 17 | release { 18 | minifyEnabled false 19 | } 20 | } 21 | compileOptions { 22 | sourceCompatibility JavaVersion.VERSION_1_8 23 | targetCompatibility JavaVersion.VERSION_1_8 24 | } 25 | packagingOptions { 26 | exclude 'META-INF/rxjava.properties' 27 | } 28 | } 29 | 30 | dependencies { 31 | compile 'io.reactivex:rxjava:1.2.3' 32 | compile 'io.reactivex:rxandroid:1.2.1' 33 | compile 'com.squareup.retrofit2:retrofit:2.1.0' 34 | compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0' 35 | compile 'com.squareup.retrofit2:converter-gson:2.1.0' 36 | compile 'com.squareup.okhttp3:okhttp:3.4.1' 37 | compile 'com.squareup.okhttp3:logging-interceptor:3.4.1' 38 | 39 | compile 'io.reactivex.rxjava2:rxjava:2.0.1' 40 | compile 'io.reactivex.rxjava2:rxandroid:2.0.1' 41 | compile 'com.jakewharton.retrofit:retrofit2-rxjava2-adapter:1.0.0' 42 | 43 | annotationProcessor 'com.github.fabioCollini.lifecyclebinder:lifecyclebinder-processor:0.3.3' 44 | compile 'com.github.fabioCollini.lifecyclebinder:lifecyclebinder-lib:0.3.3' 45 | androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', { 46 | exclude group: 'com.android.support', module: 'support-annotations' 47 | }) 48 | compile 'com.android.support:appcompat-v7:25.0.0' 49 | testCompile 'junit:junit:4.12' 50 | testCompile 'org.mockito:mockito-all:1.10.19' 51 | testCompile 'org.assertj:assertj-core:2.5.0' 52 | testCompile('com.github.ubiratansoares:rxassertions:0.3.2') { 53 | exclude group: 'io.reactivex' 54 | } 55 | 56 | provided 'com.google.auto.value:auto-value:1.3' 57 | annotationProcessor 'com.google.auto.value:auto-value:1.3' 58 | annotationProcessor 'com.ryanharter.auto.value:auto-value-gson:0.4.3' 59 | provided 'com.ryanharter.auto.value:auto-value-gson:0.4.3' 60 | annotationProcessor 'com.gabrielittner.auto.value:auto-value-with:1.0.0' 61 | } 62 | -------------------------------------------------------------------------------- /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/fabiocollini/android-sdk-macosx/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 name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /app/src/main/java/it/codingjam/testingrxjava/MainActivity.java: -------------------------------------------------------------------------------- 1 | package it.codingjam.testingrxjava; 2 | 3 | import android.os.Bundle; 4 | import android.support.v7.app.AppCompatActivity; 5 | import android.widget.TextView; 6 | import io.reactivex.android.schedulers.AndroidSchedulers; 7 | import io.reactivex.schedulers.Schedulers; 8 | import it.codingjam.testingrxjava.rxjava2.StackOverflowService; 9 | import it.codingjam.testingrxjava.rxjava2.StackOverflowServiceFactory; 10 | import it.codingjam.testingrxjava.rxjava2.UserService; 11 | 12 | public class MainActivity extends AppCompatActivity { 13 | 14 | @Override 15 | protected void onCreate(Bundle savedInstanceState) { 16 | super.onCreate(savedInstanceState); 17 | setContentView(R.layout.activity_main); 18 | StackOverflowService service = StackOverflowServiceFactory.createService(); 19 | 20 | new UserService(service) 21 | .loadUsers() 22 | .flattenAsObservable(l -> l) 23 | .reduce("", (s, userStats) -> s + "\n\n" + userStats) 24 | .subscribeOn(Schedulers.io()) 25 | .observeOn(AndroidSchedulers.mainThread()) 26 | .subscribe( 27 | s -> ((TextView) findViewById(R.id.text)).setText(s), 28 | Throwable::printStackTrace 29 | ); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /app/src/main/java/it/codingjam/testingrxjava/MainActivity1.java: -------------------------------------------------------------------------------- 1 | package it.codingjam.testingrxjava; 2 | 3 | import android.os.Bundle; 4 | import android.support.v7.app.AppCompatActivity; 5 | import android.widget.TextView; 6 | import it.codingjam.testingrxjava.rxjava1.StackOverflowService; 7 | import it.codingjam.testingrxjava.rxjava1.StackOverflowServiceFactory; 8 | import it.codingjam.testingrxjava.rxjava1.UserService; 9 | import rx.android.schedulers.AndroidSchedulers; 10 | import rx.schedulers.Schedulers; 11 | 12 | public class MainActivity1 extends AppCompatActivity { 13 | 14 | @Override 15 | protected void onCreate(Bundle savedInstanceState) { 16 | super.onCreate(savedInstanceState); 17 | setContentView(R.layout.activity_main); 18 | StackOverflowService service = StackOverflowServiceFactory.createService(); 19 | 20 | new UserService(service) 21 | .loadUsers() 22 | .flatMapIterable(l -> l) 23 | .reduce("", (s, userStats) -> s + "\n\n" + userStats) 24 | .subscribeOn(Schedulers.io()) 25 | .observeOn(AndroidSchedulers.mainThread()) 26 | .subscribe( 27 | s -> ((TextView) findViewById(R.id.text)).setText(s), 28 | Throwable::printStackTrace 29 | ); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /app/src/main/java/it/codingjam/testingrxjava/UserStats.java: -------------------------------------------------------------------------------- 1 | package it.codingjam.testingrxjava; 2 | 3 | import com.google.auto.value.AutoValue; 4 | import com.google.gson.Gson; 5 | import com.google.gson.TypeAdapter; 6 | import it.codingjam.testingrxjava.gson.Badge; 7 | import it.codingjam.testingrxjava.gson.User; 8 | import java.text.MessageFormat; 9 | import java.util.List; 10 | 11 | @AutoValue 12 | public abstract class UserStats { 13 | 14 | public static UserStats create(User user, List badges) { 15 | return new AutoValue_UserStats(user, badges); 16 | } 17 | 18 | public static TypeAdapter typeAdapter(Gson gson) { 19 | return new AutoValue_UserStats.GsonTypeAdapter(gson); 20 | } 21 | 22 | public abstract User user(); 23 | 24 | public abstract List badges(); 25 | 26 | public int id() { 27 | return user().id(); 28 | } 29 | 30 | public int reputation() { 31 | return user().reputation(); 32 | } 33 | 34 | @Override public String toString() { 35 | return MessageFormat.format("{0}\n{1}", user().toString(), listToString(badges())); 36 | } 37 | 38 | private String listToString(List l) { 39 | String s = l.toString(); 40 | return s.substring(1, s.length() - 1); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /app/src/main/java/it/codingjam/testingrxjava/gson/Badge.java: -------------------------------------------------------------------------------- 1 | package it.codingjam.testingrxjava.gson; 2 | 3 | import com.google.auto.value.AutoValue; 4 | import com.google.gson.Gson; 5 | import com.google.gson.TypeAdapter; 6 | 7 | @AutoValue 8 | public abstract class Badge { 9 | 10 | public static Badge create(String name) { 11 | return new AutoValue_Badge(name); 12 | } 13 | 14 | public static TypeAdapter typeAdapter(Gson gson) { 15 | return new AutoValue_Badge.GsonTypeAdapter(gson); 16 | } 17 | 18 | public abstract String name(); 19 | 20 | @Override public String toString() { 21 | return name(); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /app/src/main/java/it/codingjam/testingrxjava/gson/BadgeResponse.java: -------------------------------------------------------------------------------- 1 | package it.codingjam.testingrxjava.gson; 2 | 3 | import com.google.auto.value.AutoValue; 4 | import com.google.gson.Gson; 5 | import com.google.gson.TypeAdapter; 6 | import java.util.Arrays; 7 | import java.util.List; 8 | 9 | @AutoValue 10 | public abstract class BadgeResponse { 11 | public static BadgeResponse create(List items) { 12 | return new AutoValue_BadgeResponse(items); 13 | } 14 | 15 | public static BadgeResponse create(Badge... items) { 16 | return new AutoValue_BadgeResponse(Arrays.asList(items)); 17 | } 18 | 19 | public static TypeAdapter typeAdapter(Gson gson) { 20 | return new AutoValue_BadgeResponse.GsonTypeAdapter(gson); 21 | } 22 | 23 | public abstract List items(); 24 | } 25 | -------------------------------------------------------------------------------- /app/src/main/java/it/codingjam/testingrxjava/gson/MyAdapterFactory.java: -------------------------------------------------------------------------------- 1 | package it.codingjam.testingrxjava.gson; 2 | 3 | import com.google.gson.TypeAdapterFactory; 4 | import com.ryanharter.auto.value.gson.GsonTypeAdapterFactory; 5 | 6 | @GsonTypeAdapterFactory 7 | public abstract class MyAdapterFactory implements TypeAdapterFactory { 8 | 9 | public static TypeAdapterFactory create() { 10 | return new AutoValueGson_MyAdapterFactory(); 11 | } 12 | } -------------------------------------------------------------------------------- /app/src/main/java/it/codingjam/testingrxjava/gson/User.java: -------------------------------------------------------------------------------- 1 | package it.codingjam.testingrxjava.gson; 2 | 3 | import android.support.annotation.Nullable; 4 | import com.google.auto.value.AutoValue; 5 | import com.google.gson.Gson; 6 | import com.google.gson.TypeAdapter; 7 | import com.google.gson.annotations.SerializedName; 8 | import java.text.MessageFormat; 9 | 10 | @AutoValue 11 | public abstract class User { 12 | 13 | public static User create(int id, int reputation, String name) { 14 | return new AutoValue_User(id, reputation, name, null); 15 | } 16 | 17 | public static User create(int id, int reputation, String name, String location) { 18 | return new AutoValue_User(id, reputation, name, location); 19 | } 20 | 21 | public static TypeAdapter typeAdapter(Gson gson) { 22 | return new AutoValue_User.GsonTypeAdapter(gson); 23 | } 24 | 25 | @SerializedName("user_id") 26 | public abstract int id(); 27 | 28 | public abstract int reputation(); 29 | 30 | @SerializedName("display_name") 31 | public abstract String name(); 32 | 33 | @Nullable 34 | public abstract String location(); 35 | 36 | @Override public String toString() { 37 | if (location() == null) { 38 | return MessageFormat.format("{0} {1}", reputation(), name()); 39 | } else { 40 | return MessageFormat.format("{0} {1} ({2})", reputation(), name(), location()); 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /app/src/main/java/it/codingjam/testingrxjava/gson/UserResponse.java: -------------------------------------------------------------------------------- 1 | package it.codingjam.testingrxjava.gson; 2 | 3 | import com.google.auto.value.AutoValue; 4 | import com.google.gson.Gson; 5 | import com.google.gson.TypeAdapter; 6 | import java.util.Arrays; 7 | import java.util.List; 8 | 9 | @AutoValue 10 | public abstract class UserResponse { 11 | public static UserResponse create(List items) { 12 | return new AutoValue_UserResponse(items); 13 | } 14 | 15 | public static UserResponse create(User... items) { 16 | return new AutoValue_UserResponse(Arrays.asList(items)); 17 | } 18 | 19 | public static TypeAdapter typeAdapter(Gson gson) { 20 | return new AutoValue_UserResponse.GsonTypeAdapter(gson); 21 | } 22 | 23 | public abstract List items(); 24 | } 25 | -------------------------------------------------------------------------------- /app/src/main/java/it/codingjam/testingrxjava/rxjava1/StackOverflowService.java: -------------------------------------------------------------------------------- 1 | package it.codingjam.testingrxjava.rxjava1; 2 | 3 | import it.codingjam.testingrxjava.gson.BadgeResponse; 4 | import it.codingjam.testingrxjava.gson.UserResponse; 5 | import retrofit2.http.GET; 6 | import retrofit2.http.Path; 7 | import rx.Observable; 8 | 9 | public interface StackOverflowService { 10 | 11 | @GET("/users") Observable getTopUsers(); 12 | 13 | @GET("/users/{userId}/badges") Observable getBadges(@Path("userId") int userId); 14 | } 15 | -------------------------------------------------------------------------------- /app/src/main/java/it/codingjam/testingrxjava/rxjava1/StackOverflowServiceFactory.java: -------------------------------------------------------------------------------- 1 | package it.codingjam.testingrxjava.rxjava1; 2 | 3 | import com.google.gson.Gson; 4 | import com.google.gson.GsonBuilder; 5 | import it.codingjam.testingrxjava.gson.MyAdapterFactory; 6 | import okhttp3.HttpUrl; 7 | import okhttp3.OkHttpClient; 8 | import okhttp3.Request; 9 | import okhttp3.logging.HttpLoggingInterceptor; 10 | import retrofit2.Retrofit; 11 | import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; 12 | import retrofit2.converter.gson.GsonConverterFactory; 13 | 14 | public class StackOverflowServiceFactory { 15 | public static StackOverflowService createService() { 16 | OkHttpClient okHttpClient = new OkHttpClient.Builder() 17 | .addInterceptor(chain -> { 18 | Request request = chain.request(); 19 | HttpUrl url = request.url().newBuilder() 20 | .addQueryParameter("site", "stackoverflow") 21 | .addQueryParameter("key", "fruiv4j48P0HjSJ8t7a8Gg((") 22 | .build(); 23 | request = request.newBuilder().url(url).build(); 24 | return chain.proceed(request); 25 | }) 26 | .addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)) 27 | .build(); 28 | 29 | Gson gson = new GsonBuilder() 30 | .registerTypeAdapterFactory(MyAdapterFactory.create()) 31 | .create(); 32 | 33 | Retrofit retrofit = new Retrofit.Builder() 34 | .baseUrl("http://api.stackexchange.com/2.2/") 35 | .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) 36 | .addConverterFactory(GsonConverterFactory.create(gson)) 37 | .client(okHttpClient) 38 | .build(); 39 | return retrofit.create(StackOverflowService.class); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /app/src/main/java/it/codingjam/testingrxjava/rxjava1/UserService.java: -------------------------------------------------------------------------------- 1 | package it.codingjam.testingrxjava.rxjava1; 2 | 3 | import it.codingjam.testingrxjava.UserStats; 4 | import it.codingjam.testingrxjava.gson.BadgeResponse; 5 | import it.codingjam.testingrxjava.gson.User; 6 | import it.codingjam.testingrxjava.gson.UserResponse; 7 | import java.util.List; 8 | import rx.Observable; 9 | import rx.schedulers.Schedulers; 10 | 11 | public class UserService { 12 | private StackOverflowService service; 13 | 14 | public UserService(StackOverflowService service) { 15 | this.service = service; 16 | } 17 | 18 | public Observable> loadUsers() { 19 | return service.getTopUsers() 20 | .flatMapIterable(UserResponse::items) 21 | .limit(5) 22 | .flatMap(this::loadUserStats) 23 | .toList(); 24 | } 25 | 26 | private Observable loadUserStats(User user) { 27 | return service.getBadges(user.id()) 28 | .subscribeOn(Schedulers.io()) 29 | .map(BadgeResponse::items) 30 | .map(badges -> UserStats.create(user, badges)); 31 | } 32 | } -------------------------------------------------------------------------------- /app/src/main/java/it/codingjam/testingrxjava/rxjava1/UserService2.java: -------------------------------------------------------------------------------- 1 | package it.codingjam.testingrxjava.rxjava1; 2 | 3 | import it.codingjam.testingrxjava.UserStats; 4 | import it.codingjam.testingrxjava.gson.BadgeResponse; 5 | import it.codingjam.testingrxjava.gson.User; 6 | import it.codingjam.testingrxjava.gson.UserResponse; 7 | import java.util.List; 8 | import rx.Observable; 9 | import rx.schedulers.Schedulers; 10 | 11 | public class UserService2 { 12 | private StackOverflowService service; 13 | 14 | public UserService2(StackOverflowService service) { 15 | this.service = service; 16 | } 17 | 18 | public Observable> loadUsers() { 19 | return service.getTopUsers() 20 | .flatMapIterable(UserResponse::items) 21 | .limit(5) 22 | .concatMap(this::loadUserStats) 23 | .toList(); 24 | } 25 | 26 | private Observable loadUserStats(User user) { 27 | return service.getBadges(user.id()) 28 | .subscribeOn(Schedulers.io()) 29 | .map(BadgeResponse::items) 30 | .map(badges -> UserStats.create(user, badges)); 31 | } 32 | } -------------------------------------------------------------------------------- /app/src/main/java/it/codingjam/testingrxjava/rxjava1/UserService3.java: -------------------------------------------------------------------------------- 1 | package it.codingjam.testingrxjava.rxjava1; 2 | 3 | import it.codingjam.testingrxjava.UserStats; 4 | import it.codingjam.testingrxjava.gson.BadgeResponse; 5 | import it.codingjam.testingrxjava.gson.User; 6 | import it.codingjam.testingrxjava.gson.UserResponse; 7 | import java.util.List; 8 | import rx.Observable; 9 | import rx.schedulers.Schedulers; 10 | 11 | public class UserService3 { 12 | private StackOverflowService service; 13 | 14 | public UserService3(StackOverflowService service) { 15 | this.service = service; 16 | } 17 | 18 | public Observable> loadUsers() { 19 | return service.getTopUsers() 20 | .flatMapIterable(UserResponse::items) 21 | .limit(5) 22 | .flatMap(this::loadUserStats) 23 | .toSortedList((u1, u2) -> 24 | u2.reputation() - u1.reputation()) 25 | .retry(1); 26 | } 27 | 28 | private Observable loadUserStats(User user) { 29 | return service.getBadges(user.id()) 30 | .subscribeOn(Schedulers.io()) 31 | .map(BadgeResponse::items) 32 | .map(badges -> UserStats.create(user, badges)); 33 | } 34 | } -------------------------------------------------------------------------------- /app/src/main/java/it/codingjam/testingrxjava/rxjava2/StackOverflowService.java: -------------------------------------------------------------------------------- 1 | package it.codingjam.testingrxjava.rxjava2; 2 | 3 | import io.reactivex.Single; 4 | import it.codingjam.testingrxjava.gson.BadgeResponse; 5 | import it.codingjam.testingrxjava.gson.UserResponse; 6 | import retrofit2.http.GET; 7 | import retrofit2.http.Path; 8 | 9 | public interface StackOverflowService { 10 | 11 | @GET("/users") Single getTopUsers(); 12 | 13 | @GET("/users/{userId}/badges") Single getBadges(@Path("userId") int userId); 14 | } 15 | -------------------------------------------------------------------------------- /app/src/main/java/it/codingjam/testingrxjava/rxjava2/StackOverflowServiceFactory.java: -------------------------------------------------------------------------------- 1 | package it.codingjam.testingrxjava.rxjava2; 2 | 3 | import com.google.gson.Gson; 4 | import com.google.gson.GsonBuilder; 5 | import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory; 6 | import it.codingjam.testingrxjava.gson.MyAdapterFactory; 7 | import okhttp3.HttpUrl; 8 | import okhttp3.OkHttpClient; 9 | import okhttp3.Request; 10 | import okhttp3.logging.HttpLoggingInterceptor; 11 | import retrofit2.Retrofit; 12 | import retrofit2.converter.gson.GsonConverterFactory; 13 | 14 | public class StackOverflowServiceFactory { 15 | public static StackOverflowService createService() { 16 | OkHttpClient okHttpClient = new OkHttpClient.Builder() 17 | .addInterceptor(chain -> { 18 | Request request = chain.request(); 19 | HttpUrl url = request.url().newBuilder() 20 | .addQueryParameter("site", "stackoverflow") 21 | .addQueryParameter("key", "fruiv4j48P0HjSJ8t7a8Gg((") 22 | .build(); 23 | request = request.newBuilder().url(url).build(); 24 | return chain.proceed(request); 25 | }) 26 | .addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)) 27 | .build(); 28 | 29 | Gson gson = new GsonBuilder() 30 | .registerTypeAdapterFactory(MyAdapterFactory.create()) 31 | .create(); 32 | 33 | Retrofit retrofit = new Retrofit.Builder() 34 | .baseUrl("http://api.stackexchange.com/2.2/") 35 | .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) 36 | .addConverterFactory(GsonConverterFactory.create(gson)) 37 | .client(okHttpClient) 38 | .build(); 39 | return retrofit.create(StackOverflowService.class); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /app/src/main/java/it/codingjam/testingrxjava/rxjava2/UserService.java: -------------------------------------------------------------------------------- 1 | package it.codingjam.testingrxjava.rxjava2; 2 | 3 | import io.reactivex.Single; 4 | import io.reactivex.schedulers.Schedulers; 5 | import it.codingjam.testingrxjava.UserStats; 6 | import it.codingjam.testingrxjava.gson.BadgeResponse; 7 | import it.codingjam.testingrxjava.gson.User; 8 | import it.codingjam.testingrxjava.gson.UserResponse; 9 | import java.util.List; 10 | 11 | public class UserService { 12 | private StackOverflowService service; 13 | 14 | public UserService(StackOverflowService service) { 15 | this.service = service; 16 | } 17 | 18 | public Single> loadUsers() { 19 | return service.getTopUsers() 20 | .flattenAsObservable(UserResponse::items) 21 | .take(5) 22 | .flatMapSingle(this::loadUserStats) 23 | .toList(); 24 | } 25 | 26 | private Single loadUserStats(User user) { 27 | return service.getBadges(user.id()) 28 | .subscribeOn(Schedulers.io()) 29 | .map(BadgeResponse::items) 30 | .map(badges -> UserStats.create(user, badges)); 31 | } 32 | } -------------------------------------------------------------------------------- /app/src/main/java/it/codingjam/testingrxjava/rxjava2/UserService2.java: -------------------------------------------------------------------------------- 1 | package it.codingjam.testingrxjava.rxjava2; 2 | 3 | import io.reactivex.Observable; 4 | import io.reactivex.Single; 5 | import io.reactivex.schedulers.Schedulers; 6 | import it.codingjam.testingrxjava.UserStats; 7 | import it.codingjam.testingrxjava.gson.BadgeResponse; 8 | import it.codingjam.testingrxjava.gson.User; 9 | import it.codingjam.testingrxjava.gson.UserResponse; 10 | import java.util.List; 11 | 12 | public class UserService2 { 13 | private StackOverflowService service; 14 | 15 | public UserService2(StackOverflowService service) { 16 | this.service = service; 17 | } 18 | 19 | public Single> loadUsers() { 20 | return service.getTopUsers() 21 | .flattenAsObservable(UserResponse::items) 22 | .take(5) 23 | .concatMap(this::loadUserStats) 24 | .toList(); 25 | } 26 | 27 | private Observable loadUserStats(User user) { 28 | return service.getBadges(user.id()) 29 | .subscribeOn(Schedulers.io()) 30 | .map(BadgeResponse::items) 31 | .map(badges -> UserStats.create(user, badges)) 32 | .toObservable(); 33 | } 34 | } -------------------------------------------------------------------------------- /app/src/main/java/it/codingjam/testingrxjava/rxjava2/UserService3.java: -------------------------------------------------------------------------------- 1 | package it.codingjam.testingrxjava.rxjava2; 2 | 3 | import io.reactivex.Single; 4 | import io.reactivex.schedulers.Schedulers; 5 | import it.codingjam.testingrxjava.UserStats; 6 | import it.codingjam.testingrxjava.gson.BadgeResponse; 7 | import it.codingjam.testingrxjava.gson.User; 8 | import it.codingjam.testingrxjava.gson.UserResponse; 9 | import java.util.List; 10 | import java.util.concurrent.TimeUnit; 11 | 12 | public class UserService3 { 13 | private StackOverflowService service; 14 | 15 | public UserService3(StackOverflowService service) { 16 | this.service = service; 17 | } 18 | 19 | public Single> loadUsers() { 20 | return service.getTopUsers() 21 | .flattenAsObservable(UserResponse::items) 22 | .take(5) 23 | .flatMapSingle(this::loadUserStats) 24 | .toSortedList((u1, u2) -> 25 | u2.reputation() - u1.reputation()) 26 | .retry(1) 27 | .timeout(20, TimeUnit.SECONDS); 28 | } 29 | 30 | private Single loadUserStats(User user) { 31 | return service.getBadges(user.id()) 32 | .subscribeOn(Schedulers.io()) 33 | .map(BadgeResponse::items) 34 | .map(badges -> UserStats.create(user, badges)); 35 | } 36 | } -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 13 | 14 | 18 | 19 | -------------------------------------------------------------------------------- /app/src/main/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fabioCollini/TestingRxJavaUsingMockito/f43602a07bda89352f9db9482a4e5d2f7be0f764/app/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fabioCollini/TestingRxJavaUsingMockito/f43602a07bda89352f9db9482a4e5d2f7be0f764/app/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fabioCollini/TestingRxJavaUsingMockito/f43602a07bda89352f9db9482a4e5d2f7be0f764/app/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fabioCollini/TestingRxJavaUsingMockito/f43602a07bda89352f9db9482a4e5d2f7be0f764/app/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fabioCollini/TestingRxJavaUsingMockito/f43602a07bda89352f9db9482a4e5d2f7be0f764/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/values-w820dp/dimens.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 64dp 6 | 7 | -------------------------------------------------------------------------------- /app/src/main/res/values/colors.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | #3F51B5 4 | #303F9F 5 | #FF4081 6 | 7 | -------------------------------------------------------------------------------- /app/src/main/res/values/dimens.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 16dp 4 | 16dp 5 | 6 | -------------------------------------------------------------------------------- /app/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | TestingRxJava 3 | 4 | -------------------------------------------------------------------------------- /app/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /app/src/test/java/it/codingjam/testingrxjava/ConditionUtils.java: -------------------------------------------------------------------------------- 1 | package it.codingjam.testingrxjava; 2 | 3 | import android.support.annotation.NonNull; 4 | import org.assertj.core.api.Condition; 5 | import rx.functions.Func1; 6 | 7 | public class ConditionUtils { 8 | @NonNull public static Condition condition(Func1 cond) { 9 | return new Condition() { 10 | @Override public boolean matches(T value) { 11 | return cond.call(value); 12 | } 13 | }; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /app/src/test/java/it/codingjam/testingrxjava/ExampleUnitTest.java: -------------------------------------------------------------------------------- 1 | package it.codingjam.testingrxjava; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.assertEquals; 6 | 7 | /** 8 | * Example local unit test, which will execute on the development machine (host). 9 | * 10 | * @see Testing documentation 11 | */ 12 | public class ExampleUnitTest { 13 | @Test 14 | public void addition_isCorrect() throws Exception { 15 | assertEquals(4, 2 + 2); 16 | } 17 | } -------------------------------------------------------------------------------- /app/src/test/java/it/codingjam/testingrxjava/ImmediateSchedulerRule.java: -------------------------------------------------------------------------------- 1 | package it.codingjam.testingrxjava; 2 | 3 | import io.reactivex.Scheduler; 4 | import io.reactivex.android.plugins.RxAndroidPlugins; 5 | import io.reactivex.plugins.RxJavaPlugins; 6 | import io.reactivex.schedulers.Schedulers; 7 | import org.junit.rules.TestRule; 8 | import org.junit.runner.Description; 9 | import org.junit.runners.model.Statement; 10 | 11 | public class ImmediateSchedulerRule implements TestRule { 12 | 13 | private final Scheduler immediate = Schedulers.trampoline(); 14 | // new Scheduler() { 15 | // @Override public Worker createWorker() { 16 | // return new ExecutorScheduler.ExecutorWorker(Runnable::run); 17 | // } 18 | //}; 19 | 20 | @Override 21 | public Statement apply(final Statement base, Description description) { 22 | return new Statement() { 23 | @Override 24 | public void evaluate() throws Throwable { 25 | RxJavaPlugins.setIoSchedulerHandler(scheduler -> immediate); 26 | RxJavaPlugins.setComputationSchedulerHandler(scheduler -> immediate); 27 | RxJavaPlugins.setNewThreadSchedulerHandler(scheduler -> immediate); 28 | RxAndroidPlugins.setMainThreadSchedulerHandler(scheduler -> immediate); 29 | 30 | try { 31 | base.evaluate(); 32 | } finally { 33 | RxJavaPlugins.reset(); 34 | RxAndroidPlugins.reset(); 35 | } 36 | } 37 | }; 38 | } 39 | } -------------------------------------------------------------------------------- /app/src/test/java/it/codingjam/testingrxjava/PredicateUtils.java: -------------------------------------------------------------------------------- 1 | package it.codingjam.testingrxjava; 2 | 3 | import io.reactivex.functions.Consumer; 4 | import io.reactivex.functions.Predicate; 5 | 6 | public class PredicateUtils { 7 | public static Predicate check(Consumer consumer) { 8 | return t -> { 9 | consumer.accept(t); 10 | return true; 11 | }; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /app/src/test/java/it/codingjam/testingrxjava/TestSchedulerRule.java: -------------------------------------------------------------------------------- 1 | package it.codingjam.testingrxjava; 2 | 3 | import io.reactivex.Scheduler; 4 | import io.reactivex.android.plugins.RxAndroidPlugins; 5 | import io.reactivex.internal.schedulers.ExecutorScheduler; 6 | import io.reactivex.plugins.RxJavaPlugins; 7 | import io.reactivex.schedulers.TestScheduler; 8 | import org.junit.rules.TestRule; 9 | import org.junit.runner.Description; 10 | import org.junit.runners.model.Statement; 11 | 12 | public class TestSchedulerRule implements TestRule { 13 | private final Scheduler immediate = new Scheduler() { 14 | @Override public Worker createWorker() { 15 | return new ExecutorScheduler.ExecutorWorker(Runnable::run); 16 | } 17 | }; 18 | 19 | private final TestScheduler testScheduler = new TestScheduler(); 20 | 21 | public TestScheduler getTestScheduler() { 22 | return testScheduler; 23 | } 24 | 25 | @Override 26 | public Statement apply(final Statement base, Description d) { 27 | return new Statement() { 28 | @Override 29 | public void evaluate() throws Throwable { 30 | RxJavaPlugins.setIoSchedulerHandler( 31 | scheduler -> testScheduler); 32 | RxJavaPlugins.setComputationSchedulerHandler( 33 | scheduler -> testScheduler); 34 | RxJavaPlugins.setNewThreadSchedulerHandler( 35 | scheduler -> testScheduler); 36 | RxAndroidPlugins.setMainThreadSchedulerHandler( 37 | scheduler -> immediate); 38 | 39 | try { 40 | base.evaluate(); 41 | } finally { 42 | RxJavaPlugins.reset(); 43 | RxAndroidPlugins.reset(); 44 | } 45 | } 46 | }; 47 | } 48 | } -------------------------------------------------------------------------------- /app/src/test/java/it/codingjam/testingrxjava/TestSchedulerRule1.java: -------------------------------------------------------------------------------- 1 | package it.codingjam.testingrxjava; 2 | 3 | import org.junit.rules.TestRule; 4 | import org.junit.runner.Description; 5 | import org.junit.runners.model.Statement; 6 | import rx.plugins.RxJavaHooks; 7 | import rx.schedulers.TestScheduler; 8 | 9 | public class TestSchedulerRule1 implements TestRule { 10 | private final TestScheduler testScheduler = new TestScheduler(); 11 | 12 | public TestScheduler getTestScheduler() { 13 | return testScheduler; 14 | } 15 | 16 | @Override 17 | public Statement apply(final Statement base, Description description) { 18 | return new Statement() { 19 | @Override 20 | public void evaluate() throws Throwable { 21 | RxJavaHooks.setOnIOScheduler(scheduler -> testScheduler); 22 | RxJavaHooks.setOnComputationScheduler(scheduler -> testScheduler); 23 | RxJavaHooks.setOnNewThreadScheduler(scheduler -> testScheduler); 24 | 25 | try { 26 | base.evaluate(); 27 | } finally { 28 | RxJavaHooks.reset(); 29 | } 30 | } 31 | }; 32 | } 33 | } -------------------------------------------------------------------------------- /app/src/test/java/it/codingjam/testingrxjava/rxjava1/UserServiceTest_1.java: -------------------------------------------------------------------------------- 1 | package it.codingjam.testingrxjava.rxjava1; 2 | 3 | import it.codingjam.testingrxjava.UserStats; 4 | import it.codingjam.testingrxjava.gson.Badge; 5 | import it.codingjam.testingrxjava.gson.BadgeResponse; 6 | import it.codingjam.testingrxjava.gson.User; 7 | import it.codingjam.testingrxjava.gson.UserResponse; 8 | import java.util.List; 9 | import org.junit.Rule; 10 | import org.junit.Test; 11 | import org.mockito.InjectMocks; 12 | import org.mockito.Mock; 13 | import org.mockito.junit.MockitoJUnit; 14 | import org.mockito.junit.MockitoRule; 15 | import rx.observers.TestSubscriber; 16 | 17 | import static java.util.Collections.singletonList; 18 | import static org.assertj.core.api.Java6Assertions.assertThat; 19 | import static org.mockito.Matchers.anyInt; 20 | import static org.mockito.Mockito.when; 21 | import static rx.Observable.just; 22 | 23 | public class UserServiceTest_1 { 24 | 25 | @Rule public MockitoRule rule = MockitoJUnit.rule(); 26 | 27 | @Mock StackOverflowService stackOverflowService; 28 | 29 | @InjectMocks UserService userService; 30 | 31 | private TestSubscriber> testSubscriber = new TestSubscriber<>(); 32 | 33 | @Test public void testSubscribe() { 34 | when(stackOverflowService.getTopUsers()) 35 | .thenReturn(just(UserResponse.create(singletonList(User.create(1, 10, "user 1", null))))); 36 | when(stackOverflowService.getBadges(anyInt())) 37 | .thenReturn(just(BadgeResponse.create(singletonList(Badge.create("badge"))))); 38 | 39 | userService.loadUsers().subscribe(testSubscriber); 40 | 41 | testSubscriber.awaitTerminalEvent(); 42 | 43 | testSubscriber.assertNoErrors(); 44 | testSubscriber.assertValueCount(1); 45 | assertThat(testSubscriber.getOnNextEvents().get(0)).hasSize(1); 46 | testSubscriber.assertCompleted(); 47 | } 48 | } -------------------------------------------------------------------------------- /app/src/test/java/it/codingjam/testingrxjava/rxjava1/UserServiceTest_2.java: -------------------------------------------------------------------------------- 1 | package it.codingjam.testingrxjava.rxjava1; 2 | 3 | import it.codingjam.testingrxjava.gson.Badge; 4 | import it.codingjam.testingrxjava.gson.BadgeResponse; 5 | import it.codingjam.testingrxjava.gson.User; 6 | import it.codingjam.testingrxjava.gson.UserResponse; 7 | import org.junit.Rule; 8 | import org.junit.Test; 9 | import org.mockito.InjectMocks; 10 | import org.mockito.Mock; 11 | import org.mockito.junit.MockitoJUnit; 12 | import org.mockito.junit.MockitoRule; 13 | 14 | import static br.ufs.github.rxassertions.RxAssertions.assertThat; 15 | import static it.codingjam.testingrxjava.ConditionUtils.condition; 16 | import static org.mockito.Matchers.anyInt; 17 | import static org.mockito.Mockito.when; 18 | import static rx.Observable.just; 19 | 20 | public class UserServiceTest_2 { 21 | 22 | @Rule public MockitoRule rule = MockitoJUnit.rule(); 23 | 24 | @Mock StackOverflowService stackOverflowService; 25 | 26 | @InjectMocks UserService userService; 27 | 28 | @Test public void testSubscribe() { 29 | when(stackOverflowService.getTopUsers()) 30 | .thenReturn(just(UserResponse.create(User.create(1, 100, "user 1")))); 31 | when(stackOverflowService.getBadges(anyInt())) 32 | .thenReturn(just(BadgeResponse.create(Badge.create("badge")))); 33 | 34 | assertThat(userService.loadUsers()) 35 | .withoutErrors() 36 | .emissionsCount(1) 37 | .eachItemMatches(condition(v -> v.size() == 1)) 38 | .completes(); 39 | } 40 | } -------------------------------------------------------------------------------- /app/src/test/java/it/codingjam/testingrxjava/rxjava1/UserServiceTest_3.java: -------------------------------------------------------------------------------- 1 | package it.codingjam.testingrxjava.rxjava1; 2 | 3 | import it.codingjam.testingrxjava.UserStats; 4 | import it.codingjam.testingrxjava.gson.Badge; 5 | import it.codingjam.testingrxjava.gson.BadgeResponse; 6 | import it.codingjam.testingrxjava.gson.User; 7 | import it.codingjam.testingrxjava.gson.UserResponse; 8 | import java.util.List; 9 | import org.assertj.core.api.Assertions; 10 | import org.junit.Rule; 11 | import org.junit.Test; 12 | import org.mockito.InjectMocks; 13 | import org.mockito.Mock; 14 | import org.mockito.junit.MockitoJUnit; 15 | import org.mockito.junit.MockitoRule; 16 | import rx.observers.TestSubscriber; 17 | 18 | import static br.ufs.github.rxassertions.RxAssertions.assertThat; 19 | import static it.codingjam.testingrxjava.ConditionUtils.condition; 20 | import static org.mockito.Matchers.anyInt; 21 | import static org.mockito.Mockito.when; 22 | import static rx.Observable.just; 23 | 24 | public class UserServiceTest_3 { 25 | 26 | @Rule public MockitoRule rule = MockitoJUnit.rule(); 27 | 28 | @Mock StackOverflowService stackOverflowService; 29 | 30 | @InjectMocks UserService userService; 31 | 32 | @Test public void testSubscribe() { 33 | when(stackOverflowService.getTopUsers()) 34 | .thenReturn(just(UserResponse.create( 35 | User.create(1, 100, "user 1"), 36 | User.create(2, 100, "user 2") 37 | ))); 38 | when(stackOverflowService.getBadges(anyInt())) 39 | .thenReturn(just(BadgeResponse.create(Badge.create("badge")))); 40 | 41 | assertThat(userService.loadUsers()) 42 | .withoutErrors() 43 | .emissionsCount(1) 44 | .eachItemMatches(condition(v -> v.size() == 2)) 45 | .completes(); 46 | 47 | TestSubscriber> subscriber = new TestSubscriber<>(); 48 | userService.loadUsers().subscribe(subscriber); 49 | 50 | subscriber.awaitTerminalEvent(); 51 | 52 | Assertions.assertThat(subscriber.getOnNextEvents().get(0)) 53 | .hasSize(2) 54 | .extracting(UserStats::id) 55 | .containsExactly(1, 2); 56 | } 57 | } -------------------------------------------------------------------------------- /app/src/test/java/it/codingjam/testingrxjava/rxjava1/UserServiceTest_4.java: -------------------------------------------------------------------------------- 1 | package it.codingjam.testingrxjava.rxjava1; 2 | 3 | import it.codingjam.testingrxjava.UserStats; 4 | import it.codingjam.testingrxjava.gson.Badge; 5 | import it.codingjam.testingrxjava.gson.BadgeResponse; 6 | import it.codingjam.testingrxjava.gson.User; 7 | import it.codingjam.testingrxjava.gson.UserResponse; 8 | import java.util.List; 9 | import java.util.concurrent.TimeUnit; 10 | import org.assertj.core.api.Assertions; 11 | import org.junit.Rule; 12 | import org.junit.Test; 13 | import org.mockito.InjectMocks; 14 | import org.mockito.Mock; 15 | import org.mockito.junit.MockitoJUnit; 16 | import org.mockito.junit.MockitoRule; 17 | import rx.observers.TestSubscriber; 18 | 19 | import static org.mockito.Matchers.eq; 20 | import static org.mockito.Mockito.when; 21 | import static rx.Observable.just; 22 | 23 | public class UserServiceTest_4 { 24 | 25 | @Rule public MockitoRule rule = MockitoJUnit.rule(); 26 | 27 | @Mock StackOverflowService stackOverflowService; 28 | 29 | @InjectMocks UserService userService; 30 | 31 | @Test public void testSubscribe() { 32 | when(stackOverflowService.getTopUsers()) 33 | .thenReturn(just(UserResponse.create( 34 | User.create(1, 100, "user 1"), 35 | User.create(2, 100, "user 2") 36 | ))); 37 | when(stackOverflowService.getBadges(eq(1))).thenReturn( 38 | just(BadgeResponse.create(Badge.create("badge1"))) 39 | .delay(2, TimeUnit.SECONDS)); 40 | when(stackOverflowService.getBadges(eq(2))).thenReturn( 41 | just(BadgeResponse.create(Badge.create("badge2"))) 42 | .delay(1, TimeUnit.SECONDS)); 43 | 44 | TestSubscriber> subscriber = new TestSubscriber<>(); 45 | userService.loadUsers().subscribe(subscriber); 46 | 47 | subscriber.awaitTerminalEvent(); 48 | 49 | Assertions.assertThat(subscriber.getOnNextEvents().get(0)) 50 | .hasSize(2) 51 | .extracting(UserStats::id) 52 | .containsExactly(1, 2); 53 | } 54 | } -------------------------------------------------------------------------------- /app/src/test/java/it/codingjam/testingrxjava/rxjava1/UserServiceTest_5.java: -------------------------------------------------------------------------------- 1 | package it.codingjam.testingrxjava.rxjava1; 2 | 3 | import it.codingjam.testingrxjava.TestSchedulerRule1; 4 | import it.codingjam.testingrxjava.UserStats; 5 | import it.codingjam.testingrxjava.gson.Badge; 6 | import it.codingjam.testingrxjava.gson.BadgeResponse; 7 | import it.codingjam.testingrxjava.gson.User; 8 | import it.codingjam.testingrxjava.gson.UserResponse; 9 | import java.util.List; 10 | import java.util.concurrent.TimeUnit; 11 | import org.assertj.core.api.Assertions; 12 | import org.junit.Rule; 13 | import org.junit.Test; 14 | import org.mockito.InjectMocks; 15 | import org.mockito.Mock; 16 | import org.mockito.junit.MockitoJUnit; 17 | import org.mockito.junit.MockitoRule; 18 | import rx.observers.TestSubscriber; 19 | 20 | import static org.mockito.Matchers.eq; 21 | import static org.mockito.Mockito.when; 22 | import static rx.Observable.just; 23 | 24 | public class UserServiceTest_5 { 25 | 26 | @Rule public MockitoRule rule = MockitoJUnit.rule(); 27 | 28 | @Rule public TestSchedulerRule1 testSchedulerRule = new TestSchedulerRule1(); 29 | 30 | @Mock StackOverflowService stackOverflowService; 31 | 32 | @InjectMocks UserService userService; 33 | 34 | @Test public void testSubscribe() { 35 | when(stackOverflowService.getTopUsers()) 36 | .thenReturn(just(UserResponse.create( 37 | User.create(1, 100, "user 1"), 38 | User.create(2, 100, "user 2") 39 | ))); 40 | when(stackOverflowService.getBadges(eq(1))).thenReturn( 41 | just(BadgeResponse.create(Badge.create("badge1"))) 42 | .delay(2, TimeUnit.SECONDS)); 43 | when(stackOverflowService.getBadges(eq(2))).thenReturn( 44 | just(BadgeResponse.create(Badge.create("badge2"))) 45 | .delay(1, TimeUnit.SECONDS)); 46 | 47 | TestSubscriber> subscriber = new TestSubscriber<>(); 48 | userService.loadUsers().subscribe(subscriber); 49 | 50 | testSchedulerRule.getTestScheduler().advanceTimeBy(2, TimeUnit.SECONDS); 51 | 52 | Assertions.assertThat(subscriber.getOnNextEvents().get(0)) 53 | .hasSize(2) 54 | .extracting(UserStats::id) 55 | .containsExactly(1, 2); 56 | } 57 | } -------------------------------------------------------------------------------- /app/src/test/java/it/codingjam/testingrxjava/rxjava1/UserServiceTest_6.java: -------------------------------------------------------------------------------- 1 | package it.codingjam.testingrxjava.rxjava1; 2 | 3 | import it.codingjam.testingrxjava.TestSchedulerRule1; 4 | import it.codingjam.testingrxjava.UserStats; 5 | import it.codingjam.testingrxjava.gson.Badge; 6 | import it.codingjam.testingrxjava.gson.BadgeResponse; 7 | import it.codingjam.testingrxjava.gson.User; 8 | import it.codingjam.testingrxjava.gson.UserResponse; 9 | import java.util.List; 10 | import java.util.concurrent.TimeUnit; 11 | import org.assertj.core.api.Assertions; 12 | import org.junit.Rule; 13 | import org.junit.Test; 14 | import org.mockito.InjectMocks; 15 | import org.mockito.Mock; 16 | import org.mockito.junit.MockitoJUnit; 17 | import org.mockito.junit.MockitoRule; 18 | import rx.observers.TestSubscriber; 19 | 20 | import static org.mockito.Matchers.eq; 21 | import static org.mockito.Mockito.when; 22 | import static rx.Observable.just; 23 | 24 | public class UserServiceTest_6 { 25 | 26 | @Rule public MockitoRule rule = MockitoJUnit.rule(); 27 | 28 | @Rule public TestSchedulerRule1 testSchedulerRule = new TestSchedulerRule1(); 29 | 30 | @Mock StackOverflowService stackOverflowService; 31 | 32 | @InjectMocks UserService2 userService; 33 | 34 | @Test public void testSubscribe() { 35 | when(stackOverflowService.getTopUsers()) 36 | .thenReturn(just(UserResponse.create( 37 | User.create(1, 100, "user 1"), 38 | User.create(2, 100, "user 2") 39 | ))); 40 | when(stackOverflowService.getBadges(eq(1))).thenReturn( 41 | just(BadgeResponse.create(Badge.create("badge1"))) 42 | .delay(2, TimeUnit.SECONDS)); 43 | when(stackOverflowService.getBadges(eq(2))).thenReturn( 44 | just(BadgeResponse.create(Badge.create("badge2"))) 45 | .delay(1, TimeUnit.SECONDS)); 46 | 47 | TestSubscriber> subscriber = new TestSubscriber<>(); 48 | userService.loadUsers().subscribe(subscriber); 49 | 50 | testSchedulerRule.getTestScheduler().advanceTimeBy(3, TimeUnit.SECONDS); 51 | 52 | Assertions.assertThat(subscriber.getOnNextEvents().get(0)) 53 | .hasSize(2) 54 | .extracting(UserStats::id) 55 | .containsExactly(1, 2); 56 | } 57 | } -------------------------------------------------------------------------------- /app/src/test/java/it/codingjam/testingrxjava/rxjava1/UserServiceTest_7.java: -------------------------------------------------------------------------------- 1 | package it.codingjam.testingrxjava.rxjava1; 2 | 3 | import it.codingjam.testingrxjava.TestSchedulerRule1; 4 | import it.codingjam.testingrxjava.UserStats; 5 | import it.codingjam.testingrxjava.gson.Badge; 6 | import it.codingjam.testingrxjava.gson.BadgeResponse; 7 | import it.codingjam.testingrxjava.gson.User; 8 | import it.codingjam.testingrxjava.gson.UserResponse; 9 | import java.util.List; 10 | import java.util.concurrent.TimeUnit; 11 | import org.assertj.core.api.Assertions; 12 | import org.junit.Rule; 13 | import org.junit.Test; 14 | import org.mockito.InjectMocks; 15 | import org.mockito.Mock; 16 | import org.mockito.junit.MockitoJUnit; 17 | import org.mockito.junit.MockitoRule; 18 | import rx.observers.TestSubscriber; 19 | 20 | import static org.mockito.Matchers.eq; 21 | import static org.mockito.Mockito.when; 22 | import static rx.Observable.just; 23 | 24 | public class UserServiceTest_7 { 25 | 26 | @Rule public MockitoRule rule = MockitoJUnit.rule(); 27 | 28 | @Rule public TestSchedulerRule1 testSchedulerRule = new TestSchedulerRule1(); 29 | 30 | @Mock StackOverflowService stackOverflowService; 31 | 32 | @InjectMocks UserService3 userService; 33 | 34 | @Test public void testSubscribe() { 35 | when(stackOverflowService.getTopUsers()) 36 | .thenReturn(just(UserResponse.create( 37 | User.create(1, 200, "user 1"), 38 | User.create(2, 100, "user 2") 39 | ))); 40 | when(stackOverflowService.getBadges(eq(1))).thenReturn( 41 | just(BadgeResponse.create(Badge.create("badge1"))) 42 | .delay(2, TimeUnit.SECONDS)); 43 | when(stackOverflowService.getBadges(eq(2))).thenReturn( 44 | just(BadgeResponse.create(Badge.create("badge2"))) 45 | .delay(1, TimeUnit.SECONDS)); 46 | 47 | TestSubscriber> subscriber = new TestSubscriber<>(); 48 | userService.loadUsers().subscribe(subscriber); 49 | 50 | testSchedulerRule.getTestScheduler().advanceTimeBy(2, TimeUnit.SECONDS); 51 | 52 | Assertions.assertThat(subscriber.getOnNextEvents().get(0)) 53 | .hasSize(2) 54 | .extracting(UserStats::id) 55 | .containsExactly(1, 2); 56 | } 57 | } -------------------------------------------------------------------------------- /app/src/test/java/it/codingjam/testingrxjava/rxjava1/UserServiceTest_8.java: -------------------------------------------------------------------------------- 1 | package it.codingjam.testingrxjava.rxjava1; 2 | 3 | import it.codingjam.testingrxjava.UserStats; 4 | import it.codingjam.testingrxjava.gson.Badge; 5 | import it.codingjam.testingrxjava.gson.BadgeResponse; 6 | import it.codingjam.testingrxjava.gson.User; 7 | import it.codingjam.testingrxjava.gson.UserResponse; 8 | import java.util.List; 9 | import java.util.concurrent.Callable; 10 | import org.assertj.core.api.Assertions; 11 | import org.junit.Rule; 12 | import org.junit.Test; 13 | import org.mockito.InjectMocks; 14 | import org.mockito.Mock; 15 | import org.mockito.junit.MockitoJUnit; 16 | import org.mockito.junit.MockitoRule; 17 | import rx.Observable; 18 | import rx.observers.TestSubscriber; 19 | 20 | import static org.mockito.Matchers.eq; 21 | import static org.mockito.Mockito.when; 22 | import static rx.Observable.just; 23 | 24 | public class UserServiceTest_8 { 25 | 26 | @Rule public MockitoRule rule = MockitoJUnit.rule(); 27 | 28 | @Mock StackOverflowService stackOverflowService; 29 | 30 | @InjectMocks UserService3 userService; 31 | 32 | @Test public void testErrorOnBadge() { 33 | when(stackOverflowService.getTopUsers()) 34 | .thenReturn(just(UserResponse.create( 35 | User.create(1, 200, "user 1"), 36 | User.create(2, 100, "user 2") 37 | ))); 38 | when(stackOverflowService.getBadges(eq(1))) 39 | .thenThrow(new RuntimeException(":(")) 40 | .thenReturn( 41 | just(BadgeResponse.create(Badge.create("badge1"))) 42 | ); 43 | when(stackOverflowService.getBadges(eq(2))).thenReturn( 44 | just(BadgeResponse.create(Badge.create("badge2"))) 45 | ); 46 | 47 | TestSubscriber> subscriber = new TestSubscriber<>(); 48 | userService.loadUsers().subscribe(subscriber); 49 | 50 | subscriber.awaitTerminalEvent(); 51 | subscriber.assertNoErrors(); 52 | 53 | Assertions.assertThat(subscriber.getOnNextEvents().get(0)) 54 | .hasSize(2) 55 | .extracting(UserStats::id) 56 | .containsExactly(1, 2); 57 | } 58 | 59 | @Test public void testErrorOnTopUsers() { 60 | when(stackOverflowService.getTopUsers()) 61 | .thenReturn(Observable.fromCallable(new Callable() { 62 | private boolean firstEmitted; 63 | 64 | @Override public UserResponse call() throws Exception { 65 | if (!firstEmitted) { 66 | firstEmitted = true; 67 | throw new RuntimeException(":("); 68 | } else { 69 | return UserResponse.create( 70 | User.create(1, 200, "user 1"), 71 | User.create(2, 100, "user 2") 72 | ); 73 | } 74 | } 75 | })); 76 | when(stackOverflowService.getBadges(eq(1))).thenReturn( 77 | just(BadgeResponse.create(Badge.create("badge1"))) 78 | ); 79 | when(stackOverflowService.getBadges(eq(2))).thenReturn( 80 | just(BadgeResponse.create(Badge.create("badge2"))) 81 | ); 82 | 83 | TestSubscriber> subscriber = new TestSubscriber<>(); 84 | userService.loadUsers().subscribe(subscriber); 85 | 86 | subscriber.awaitTerminalEvent(); 87 | subscriber.assertNoErrors(); 88 | Assertions.assertThat(subscriber.getOnNextEvents().get(0)) 89 | .hasSize(2) 90 | .extracting(UserStats::id) 91 | .containsExactly(1, 2); 92 | } 93 | } -------------------------------------------------------------------------------- /app/src/test/java/it/codingjam/testingrxjava/rxjava2/UserServiceTest_1.java: -------------------------------------------------------------------------------- 1 | package it.codingjam.testingrxjava.rxjava2; 2 | 3 | import io.reactivex.observers.TestObserver; 4 | import it.codingjam.testingrxjava.TestSchedulerRule; 5 | import it.codingjam.testingrxjava.UserStats; 6 | import it.codingjam.testingrxjava.gson.Badge; 7 | import it.codingjam.testingrxjava.gson.BadgeResponse; 8 | import it.codingjam.testingrxjava.gson.User; 9 | import it.codingjam.testingrxjava.gson.UserResponse; 10 | import java.util.List; 11 | import java.util.concurrent.TimeUnit; 12 | import java.util.concurrent.TimeoutException; 13 | import org.junit.Rule; 14 | import org.junit.Test; 15 | import org.mockito.InjectMocks; 16 | import org.mockito.Mock; 17 | import org.mockito.junit.MockitoJUnit; 18 | import org.mockito.junit.MockitoRule; 19 | 20 | import static io.reactivex.Single.just; 21 | import static it.codingjam.testingrxjava.PredicateUtils.check; 22 | import static org.assertj.core.api.Java6Assertions.assertThat; 23 | import static org.mockito.Matchers.eq; 24 | import static org.mockito.Mockito.when; 25 | 26 | public class UserServiceTest_1 { 27 | 28 | @Rule public MockitoRule rule = MockitoJUnit.rule(); 29 | 30 | @Rule public TestSchedulerRule testSchedulerRule = new TestSchedulerRule(); 31 | 32 | @Mock StackOverflowService stackOverflowService; 33 | 34 | @InjectMocks UserService3 userService; 35 | 36 | @Test public void checkIdsUsingDelays() { 37 | when(stackOverflowService.getTopUsers()).thenReturn( 38 | just(UserResponse.create( 39 | User.create(1, 200, "user 1"), 40 | User.create(2, 100, "user 2") 41 | )) 42 | ); 43 | when(stackOverflowService.getBadges(eq(1))).thenReturn( 44 | just(BadgeResponse.create(Badge.create("badge1"))) 45 | .delay(2, TimeUnit.SECONDS)); 46 | when(stackOverflowService.getBadges(eq(2))).thenReturn( 47 | just(BadgeResponse.create(Badge.create("badge2"))) 48 | .delay(1, TimeUnit.SECONDS)); 49 | 50 | TestObserver> testObserver = userService.loadUsers().test(); 51 | 52 | testSchedulerRule.getTestScheduler().advanceTimeBy(2, TimeUnit.SECONDS); 53 | 54 | testObserver 55 | .assertNoErrors() 56 | .assertValue(check( 57 | l -> assertThat(l) 58 | .extracting(UserStats::id) 59 | .containsExactly(1, 2) 60 | )); 61 | } 62 | 63 | @Test 64 | public void timeout() throws Exception { 65 | when(stackOverflowService.getTopUsers()).thenReturn( 66 | just(UserResponse.create( 67 | User.create(1, 200, "user 1"), 68 | User.create(2, 100, "user 2") 69 | )).delay(10, TimeUnit.SECONDS) 70 | ); 71 | when(stackOverflowService.getBadges(eq(1))).thenReturn( 72 | just(BadgeResponse.create(Badge.create("badge1"))) 73 | .delay(2, TimeUnit.SECONDS)); 74 | when(stackOverflowService.getBadges(eq(2))).thenReturn( 75 | just(BadgeResponse.create(Badge.create("badge2"))) 76 | .delay(11, TimeUnit.SECONDS)); 77 | 78 | TestObserver> testObserver = userService.loadUsers().test(); 79 | 80 | testSchedulerRule.getTestScheduler().advanceTimeBy(20, TimeUnit.SECONDS); 81 | 82 | testObserver.assertError(TimeoutException.class); 83 | } 84 | } -------------------------------------------------------------------------------- /app/src/test/java/it/codingjam/testingrxjava/rxjava2/UserServiceTest_2.java: -------------------------------------------------------------------------------- 1 | package it.codingjam.testingrxjava.rxjava2; 2 | 3 | import org.junit.Rule; 4 | import org.junit.Test; 5 | import org.mockito.InjectMocks; 6 | import org.mockito.Mock; 7 | import org.mockito.junit.MockitoJUnit; 8 | import org.mockito.junit.MockitoRule; 9 | 10 | public class UserServiceTest_2 { 11 | 12 | @Rule public MockitoRule rule = MockitoJUnit.rule(); 13 | 14 | @Mock StackOverflowService stackOverflowService; 15 | 16 | @InjectMocks UserService userService; 17 | 18 | @Test public void emptyTest() { 19 | userService.loadUsers(); 20 | } 21 | } -------------------------------------------------------------------------------- /app/src/test/java/it/codingjam/testingrxjava/rxjava2/UserServiceTest_3.java: -------------------------------------------------------------------------------- 1 | package it.codingjam.testingrxjava.rxjava2; 2 | 3 | import it.codingjam.testingrxjava.ImmediateSchedulerRule; 4 | import it.codingjam.testingrxjava.gson.Badge; 5 | import it.codingjam.testingrxjava.gson.BadgeResponse; 6 | import it.codingjam.testingrxjava.gson.User; 7 | import it.codingjam.testingrxjava.gson.UserResponse; 8 | import org.junit.Rule; 9 | import org.junit.Test; 10 | import org.mockito.InjectMocks; 11 | import org.mockito.Mock; 12 | import org.mockito.junit.MockitoJUnit; 13 | import org.mockito.junit.MockitoRule; 14 | 15 | import static io.reactivex.Single.just; 16 | import static org.mockito.Matchers.anyInt; 17 | import static org.mockito.Mockito.when; 18 | 19 | public class UserServiceTest_3 { 20 | 21 | @Rule public MockitoRule rule = MockitoJUnit.rule(); 22 | 23 | @Rule public ImmediateSchedulerRule immediateSchedulerRule = new ImmediateSchedulerRule(); 24 | 25 | @Mock StackOverflowService stackOverflowService; 26 | 27 | @InjectMocks UserService userService; 28 | 29 | @Test public void testSubscribe() { 30 | when(stackOverflowService.getTopUsers()).thenReturn( 31 | just(UserResponse.create(User.create(1, 10, "user 1"))) 32 | ); 33 | when(stackOverflowService.getBadges(anyInt())).thenReturn( 34 | just(BadgeResponse.create(Badge.create("badge"))) 35 | ); 36 | 37 | //List l = userService.loadUsers().blockingGet(); 38 | //assertThat(l).hasSize(1); 39 | 40 | userService.loadUsers().test() 41 | .assertNoErrors() 42 | .assertValue(l -> l.size() == 1); 43 | } 44 | } -------------------------------------------------------------------------------- /app/src/test/java/it/codingjam/testingrxjava/rxjava2/UserServiceTest_4.java: -------------------------------------------------------------------------------- 1 | package it.codingjam.testingrxjava.rxjava2; 2 | 3 | import io.reactivex.Observable; 4 | import io.reactivex.observers.TestObserver; 5 | import it.codingjam.testingrxjava.UserStats; 6 | import it.codingjam.testingrxjava.gson.Badge; 7 | import it.codingjam.testingrxjava.gson.BadgeResponse; 8 | import it.codingjam.testingrxjava.gson.User; 9 | import it.codingjam.testingrxjava.gson.UserResponse; 10 | import java.util.Arrays; 11 | import java.util.List; 12 | import org.junit.Rule; 13 | import org.junit.Test; 14 | import org.mockito.InjectMocks; 15 | import org.mockito.Mock; 16 | import org.mockito.junit.MockitoJUnit; 17 | import org.mockito.junit.MockitoRule; 18 | 19 | import static io.reactivex.Single.just; 20 | import static org.mockito.Matchers.anyInt; 21 | import static org.mockito.Mockito.when; 22 | 23 | public class UserServiceTest_4 { 24 | 25 | @Rule public MockitoRule rule = MockitoJUnit.rule(); 26 | 27 | @Mock StackOverflowService stackOverflowService; 28 | 29 | @InjectMocks UserService userService; 30 | 31 | @Test public void testSubscribe() { 32 | when(stackOverflowService.getTopUsers()).thenReturn( 33 | just(UserResponse.create( 34 | User.create(1, 100, "user 1"), 35 | User.create(2, 100, "user 2") 36 | )) 37 | ); 38 | when(stackOverflowService.getBadges(anyInt())).thenReturn( 39 | just(BadgeResponse.create(Badge.create("badge")))); 40 | 41 | TestObserver> testObserver = userService.loadUsers() 42 | .test(); 43 | testObserver.awaitTerminalEvent(); 44 | 45 | testObserver 46 | .assertNoErrors() 47 | .assertValue(l -> l.size() == 2) 48 | .assertValue(l -> 49 | Observable.fromIterable(l) 50 | .map(UserStats::id) 51 | .toList() 52 | .blockingGet() 53 | .equals(Arrays.asList(1, 2)) 54 | ); 55 | } 56 | } -------------------------------------------------------------------------------- /app/src/test/java/it/codingjam/testingrxjava/rxjava2/UserServiceTest_5.java: -------------------------------------------------------------------------------- 1 | package it.codingjam.testingrxjava.rxjava2; 2 | 3 | import io.reactivex.observers.TestObserver; 4 | import it.codingjam.testingrxjava.UserStats; 5 | import it.codingjam.testingrxjava.gson.Badge; 6 | import it.codingjam.testingrxjava.gson.BadgeResponse; 7 | import it.codingjam.testingrxjava.gson.User; 8 | import it.codingjam.testingrxjava.gson.UserResponse; 9 | import java.util.List; 10 | import org.junit.Rule; 11 | import org.junit.Test; 12 | import org.mockito.InjectMocks; 13 | import org.mockito.Mock; 14 | import org.mockito.junit.MockitoJUnit; 15 | import org.mockito.junit.MockitoRule; 16 | 17 | import static io.reactivex.Single.just; 18 | import static it.codingjam.testingrxjava.PredicateUtils.check; 19 | import static org.assertj.core.api.Java6Assertions.assertThat; 20 | import static org.mockito.Matchers.eq; 21 | import static org.mockito.Mockito.when; 22 | 23 | public class UserServiceTest_5 { 24 | 25 | @Rule public MockitoRule rule = MockitoJUnit.rule(); 26 | 27 | @Mock StackOverflowService stackOverflowService; 28 | 29 | @InjectMocks UserService userService; 30 | 31 | @Test public void testSubscribe() { 32 | when(stackOverflowService.getTopUsers()).thenReturn( 33 | just(UserResponse.create( 34 | User.create(1, 100, "user 1"), 35 | User.create(2, 100, "user 2") 36 | ) 37 | )); 38 | when(stackOverflowService.getBadges(eq(1))).thenReturn( 39 | just(BadgeResponse.create(Badge.create("badge1"))) 40 | //.delay(2, TimeUnit.SECONDS) 41 | ); 42 | when(stackOverflowService.getBadges(eq(2))).thenReturn( 43 | just(BadgeResponse.create(Badge.create("badge2"))) 44 | //.delay(1, TimeUnit.SECONDS) 45 | ); 46 | 47 | TestObserver> testObserver = userService.loadUsers().test(); 48 | 49 | testObserver.awaitTerminalEvent(); 50 | 51 | testObserver 52 | .assertNoErrors() 53 | .assertValue(check( 54 | l -> assertThat(l) 55 | .extracting(UserStats::id) 56 | .containsExactly(1, 2) 57 | )); 58 | } 59 | } -------------------------------------------------------------------------------- /app/src/test/java/it/codingjam/testingrxjava/rxjava2/UserServiceTest_6.java: -------------------------------------------------------------------------------- 1 | package it.codingjam.testingrxjava.rxjava2; 2 | 3 | import io.reactivex.observers.TestObserver; 4 | import it.codingjam.testingrxjava.TestSchedulerRule; 5 | import it.codingjam.testingrxjava.UserStats; 6 | import it.codingjam.testingrxjava.gson.Badge; 7 | import it.codingjam.testingrxjava.gson.BadgeResponse; 8 | import it.codingjam.testingrxjava.gson.User; 9 | import it.codingjam.testingrxjava.gson.UserResponse; 10 | import java.util.List; 11 | import java.util.concurrent.TimeUnit; 12 | import org.junit.Rule; 13 | import org.junit.Test; 14 | import org.mockito.InjectMocks; 15 | import org.mockito.Mock; 16 | import org.mockito.junit.MockitoJUnit; 17 | import org.mockito.junit.MockitoRule; 18 | 19 | import static io.reactivex.Single.just; 20 | import static it.codingjam.testingrxjava.PredicateUtils.check; 21 | import static org.assertj.core.api.Java6Assertions.assertThat; 22 | import static org.mockito.Matchers.eq; 23 | import static org.mockito.Mockito.when; 24 | 25 | public class UserServiceTest_6 { 26 | 27 | @Rule public MockitoRule rule = MockitoJUnit.rule(); 28 | 29 | @Rule public TestSchedulerRule testSchedulerRule = new TestSchedulerRule(); 30 | 31 | @Mock StackOverflowService stackOverflowService; 32 | 33 | @InjectMocks UserService userService; 34 | 35 | @Test public void testSubscribe() { 36 | when(stackOverflowService.getTopUsers()) 37 | .thenReturn(just(UserResponse.create( 38 | User.create(1, 100, "user 1"), 39 | User.create(2, 100, "user 2") 40 | ))); 41 | when(stackOverflowService.getBadges(eq(1))).thenReturn( 42 | just(BadgeResponse.create(Badge.create("badge1"))) 43 | .delay(2, TimeUnit.SECONDS)); 44 | when(stackOverflowService.getBadges(eq(2))).thenReturn( 45 | just(BadgeResponse.create(Badge.create("badge2"))) 46 | .delay(1, TimeUnit.SECONDS)); 47 | 48 | TestObserver> testObserver = userService.loadUsers().test(); 49 | 50 | testSchedulerRule.getTestScheduler().advanceTimeBy(2, TimeUnit.SECONDS); 51 | 52 | testObserver 53 | .assertNoErrors() 54 | .assertValue(check( 55 | l -> assertThat(l) 56 | .extracting(UserStats::id) 57 | .containsExactly(1, 2) 58 | )); 59 | } 60 | } -------------------------------------------------------------------------------- /app/src/test/java/it/codingjam/testingrxjava/rxjava2/UserServiceTest_7.java: -------------------------------------------------------------------------------- 1 | package it.codingjam.testingrxjava.rxjava2; 2 | 3 | import io.reactivex.observers.TestObserver; 4 | import it.codingjam.testingrxjava.TestSchedulerRule; 5 | import it.codingjam.testingrxjava.UserStats; 6 | import it.codingjam.testingrxjava.gson.Badge; 7 | import it.codingjam.testingrxjava.gson.BadgeResponse; 8 | import it.codingjam.testingrxjava.gson.User; 9 | import it.codingjam.testingrxjava.gson.UserResponse; 10 | import java.util.List; 11 | import java.util.concurrent.TimeUnit; 12 | import org.junit.Rule; 13 | import org.junit.Test; 14 | import org.mockito.InjectMocks; 15 | import org.mockito.Mock; 16 | import org.mockito.junit.MockitoJUnit; 17 | import org.mockito.junit.MockitoRule; 18 | 19 | import static io.reactivex.Single.just; 20 | import static it.codingjam.testingrxjava.PredicateUtils.check; 21 | import static org.assertj.core.api.Java6Assertions.assertThat; 22 | import static org.mockito.Matchers.eq; 23 | import static org.mockito.Mockito.when; 24 | 25 | public class UserServiceTest_7 { 26 | 27 | @Rule public MockitoRule rule = MockitoJUnit.rule(); 28 | 29 | @Rule public TestSchedulerRule testSchedulerRule = new TestSchedulerRule(); 30 | 31 | @Mock StackOverflowService stackOverflowService; 32 | 33 | @InjectMocks UserService2 userService; 34 | 35 | @Test public void testSubscribe() { 36 | when(stackOverflowService.getTopUsers()) 37 | .thenReturn(just(UserResponse.create( 38 | User.create(1, 100, "user 1"), 39 | User.create(2, 100, "user 2") 40 | ))); 41 | when(stackOverflowService.getBadges(eq(1))).thenReturn( 42 | just(BadgeResponse.create(Badge.create("badge1"))) 43 | .delay(2, TimeUnit.SECONDS)); 44 | when(stackOverflowService.getBadges(eq(2))).thenReturn( 45 | just(BadgeResponse.create(Badge.create("badge2"))) 46 | .delay(1, TimeUnit.SECONDS)); 47 | 48 | TestObserver> testObserver = userService.loadUsers().test(); 49 | 50 | testSchedulerRule.getTestScheduler().advanceTimeBy(3, TimeUnit.SECONDS); 51 | 52 | testObserver 53 | .assertNoErrors() 54 | .assertValue(check( 55 | l -> assertThat(l) 56 | .extracting(UserStats::id) 57 | .containsExactly(1, 2) 58 | )); 59 | } 60 | } -------------------------------------------------------------------------------- /app/src/test/java/it/codingjam/testingrxjava/rxjava2/UserServiceTest_8.java: -------------------------------------------------------------------------------- 1 | package it.codingjam.testingrxjava.rxjava2; 2 | 3 | import io.reactivex.Single; 4 | import io.reactivex.observers.TestObserver; 5 | import it.codingjam.testingrxjava.TestSchedulerRule; 6 | import it.codingjam.testingrxjava.UserStats; 7 | import it.codingjam.testingrxjava.gson.Badge; 8 | import it.codingjam.testingrxjava.gson.BadgeResponse; 9 | import it.codingjam.testingrxjava.gson.User; 10 | import it.codingjam.testingrxjava.gson.UserResponse; 11 | import java.util.List; 12 | import java.util.concurrent.Callable; 13 | import org.junit.Rule; 14 | import org.junit.Test; 15 | import org.mockito.InjectMocks; 16 | import org.mockito.Mock; 17 | import org.mockito.junit.MockitoJUnit; 18 | import org.mockito.junit.MockitoRule; 19 | 20 | import static io.reactivex.Single.just; 21 | import static it.codingjam.testingrxjava.PredicateUtils.check; 22 | import static org.assertj.core.api.Java6Assertions.assertThat; 23 | import static org.mockito.Matchers.eq; 24 | import static org.mockito.Mockito.when; 25 | 26 | public class UserServiceTest_8 { 27 | 28 | @Rule public MockitoRule rule = MockitoJUnit.rule(); 29 | 30 | @Rule public TestSchedulerRule testSchedulerRule = new TestSchedulerRule(); 31 | 32 | @Mock StackOverflowService stackOverflowService; 33 | 34 | @InjectMocks UserService3 userService; 35 | 36 | @Test public void testErrorOnBadge() { 37 | when(stackOverflowService.getTopUsers()).thenReturn( 38 | just(UserResponse.create( 39 | User.create(1, 200, "user 1"), 40 | User.create(2, 100, "user 2") 41 | )) 42 | ); 43 | when(stackOverflowService.getBadges(eq(1))) 44 | .thenThrow(new RuntimeException(":(")) 45 | .thenReturn( 46 | just(BadgeResponse.create(Badge.create("badge1"))) 47 | ); 48 | when(stackOverflowService.getBadges(eq(2))).thenReturn( 49 | just(BadgeResponse.create(Badge.create("badge2"))) 50 | ); 51 | 52 | TestObserver> testObserver = userService.loadUsers().test(); 53 | testSchedulerRule.getTestScheduler().triggerActions(); 54 | 55 | testObserver 56 | .assertNoErrors() 57 | .assertValue(check( 58 | l -> assertThat(l) 59 | .extracting(UserStats::id) 60 | .containsExactly(1, 2) 61 | )); 62 | } 63 | 64 | @Test public void testErrorOnTopUsers() { 65 | when(stackOverflowService.getTopUsers()) 66 | .thenReturn(Single.fromCallable(new Callable() { 67 | private boolean firstEmitted; 68 | 69 | @Override public UserResponse call() throws Exception { 70 | if (!firstEmitted) { 71 | firstEmitted = true; 72 | throw new RuntimeException(":("); 73 | } else { 74 | return UserResponse.create( 75 | User.create(1, 200, "user 1"), 76 | User.create(2, 100, "user 2") 77 | ); 78 | } 79 | } 80 | })); 81 | when(stackOverflowService.getBadges(eq(1))).thenReturn( 82 | just(BadgeResponse.create(Badge.create("badge1"))) 83 | ); 84 | when(stackOverflowService.getBadges(eq(2))).thenReturn( 85 | just(BadgeResponse.create(Badge.create("badge2"))) 86 | ); 87 | 88 | TestObserver> testObserver = userService.loadUsers().test(); 89 | testSchedulerRule.getTestScheduler().triggerActions(); 90 | 91 | testObserver 92 | .assertNoErrors() 93 | .assertValue(check( 94 | l -> assertThat(l) 95 | .extracting(UserStats::id) 96 | .containsExactly(1, 2) 97 | )); 98 | } 99 | } -------------------------------------------------------------------------------- /app/src/test/java/org/mockito/configuration/MockitoConfiguration.java: -------------------------------------------------------------------------------- 1 | package org.mockito.configuration; 2 | 3 | import android.support.annotation.NonNull; 4 | import io.reactivex.Observable; 5 | import io.reactivex.Single; 6 | import org.mockito.internal.stubbing.defaultanswers.ReturnsEmptyValues; 7 | import org.mockito.invocation.InvocationOnMock; 8 | import org.mockito.stubbing.Answer; 9 | 10 | public class MockitoConfiguration extends DefaultMockitoConfiguration { 11 | public Answer getDefaultAnswer() { 12 | return new ReturnsEmptyValues() { 13 | @Override 14 | public Object answer(InvocationOnMock inv) { 15 | Class type = inv.getMethod().getReturnType(); 16 | if (type.isAssignableFrom(rx.Observable.class)) { 17 | return rx.Observable.error(createException(inv, "Observable")); 18 | } else if (type.isAssignableFrom(rx.Single.class)) { 19 | return rx.Single.error(createException(inv, "Single")); 20 | } else if (type.isAssignableFrom(Observable.class)) { 21 | return Observable.error(createException(inv, "Observable")); 22 | } else if (type.isAssignableFrom(Single.class)) { 23 | return Single.error(createException(inv, "Single")); 24 | } else { 25 | return super.answer(inv); 26 | } 27 | } 28 | }; 29 | } 30 | 31 | @NonNull 32 | private RuntimeException createException(InvocationOnMock invocation, String className) { 33 | String s = invocation.toString(); 34 | return new RuntimeException("No mock defined for invocation " + s + 35 | "\nwhen(" + s.substring(0, s.length() - 1) + 36 | ").thenReturn(" + className + ".just());"); 37 | } 38 | } -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | // Top-level build file where you can add configuration options common to all sub-projects/modules. 2 | 3 | buildscript { 4 | repositories { 5 | jcenter() 6 | } 7 | dependencies { 8 | classpath 'com.android.tools.build:gradle:2.2.2' 9 | classpath 'me.tatarka:gradle-retrolambda:3.3.0' 10 | 11 | // NOTE: Do not place your application dependencies here; they belong 12 | // in the individual module build.gradle files 13 | } 14 | } 15 | 16 | allprojects { 17 | repositories { 18 | jcenter() 19 | maven { url "https://jitpack.io" } 20 | } 21 | } 22 | 23 | task clean(type: Delete) { 24 | delete rootProject.buildDir 25 | } 26 | -------------------------------------------------------------------------------- /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 | org.gradle.jvmargs=-Xmx1536m 13 | 14 | # When configured, Gradle will run in incubating parallel mode. 15 | # This option should only be used with decoupled projects. More details, visit 16 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 17 | # org.gradle.parallel=true 18 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fabioCollini/TestingRxJavaUsingMockito/f43602a07bda89352f9db9482a4e5d2f7be0f764/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Mon Dec 28 10:00:20 PST 2015 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.14.1-all.zip 7 | -------------------------------------------------------------------------------- /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 | # Attempt to set APP_HOME 46 | # Resolve links: $0 may be a link 47 | PRG="$0" 48 | # Need this for relative symlinks. 49 | while [ -h "$PRG" ] ; do 50 | ls=`ls -ld "$PRG"` 51 | link=`expr "$ls" : '.*-> \(.*\)$'` 52 | if expr "$link" : '/.*' > /dev/null; then 53 | PRG="$link" 54 | else 55 | PRG=`dirname "$PRG"`"/$link" 56 | fi 57 | done 58 | SAVED="`pwd`" 59 | cd "`dirname \"$PRG\"`/" >/dev/null 60 | APP_HOME="`pwd -P`" 61 | cd "$SAVED" >/dev/null 62 | 63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 64 | 65 | # Determine the Java command to use to start the JVM. 66 | if [ -n "$JAVA_HOME" ] ; then 67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 68 | # IBM's JDK on AIX uses strange locations for the executables 69 | JAVACMD="$JAVA_HOME/jre/sh/java" 70 | else 71 | JAVACMD="$JAVA_HOME/bin/java" 72 | fi 73 | if [ ! -x "$JAVACMD" ] ; then 74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 75 | 76 | Please set the JAVA_HOME variable in your environment to match the 77 | location of your Java installation." 78 | fi 79 | else 80 | JAVACMD="java" 81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 82 | 83 | Please set the JAVA_HOME variable in your environment to match the 84 | location of your Java installation." 85 | fi 86 | 87 | # Increase the maximum file descriptors if we can. 88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then 89 | MAX_FD_LIMIT=`ulimit -H -n` 90 | if [ $? -eq 0 ] ; then 91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 92 | MAX_FD="$MAX_FD_LIMIT" 93 | fi 94 | ulimit -n $MAX_FD 95 | if [ $? -ne 0 ] ; then 96 | warn "Could not set maximum file descriptor limit: $MAX_FD" 97 | fi 98 | else 99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 100 | fi 101 | fi 102 | 103 | # For Darwin, add options to specify how the application appears in the dock 104 | if $darwin; then 105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 106 | fi 107 | 108 | # For Cygwin, switch paths to Windows format before running java 109 | if $cygwin ; then 110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 112 | JAVACMD=`cygpath --unix "$JAVACMD"` 113 | 114 | # We build the pattern for arguments to be converted via cygpath 115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 116 | SEP="" 117 | for dir in $ROOTDIRSRAW ; do 118 | ROOTDIRS="$ROOTDIRS$SEP$dir" 119 | SEP="|" 120 | done 121 | OURCYGPATTERN="(^($ROOTDIRS))" 122 | # Add a user-defined pattern to the cygpath arguments 123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 125 | fi 126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 127 | i=0 128 | for arg in "$@" ; do 129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 131 | 132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 134 | else 135 | eval `echo args$i`="\"$arg\"" 136 | fi 137 | i=$((i+1)) 138 | done 139 | case $i in 140 | (0) set -- ;; 141 | (1) set -- "$args0" ;; 142 | (2) set -- "$args0" "$args1" ;; 143 | (3) set -- "$args0" "$args1" "$args2" ;; 144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 150 | esac 151 | fi 152 | 153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules 154 | function splitJvmOpts() { 155 | JVM_OPTS=("$@") 156 | } 157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS 158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" 159 | 160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" 161 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | include ':app' 2 | --------------------------------------------------------------------------------