SlideShare a Scribd company logo
1 of 31
Тестирование с Dagger 2
на Android
Виды тестирования
• Простые Unit тесты
• Тестирование Android компонентов
• Instrumentation тесты
public final class SourcesContract {



public interface Presenter extends MVPPresenter<SourcesView> {



void openArticles(final @NonNull NewsSourceDto source);

}



public interface Starter {



void openArticles(final @NonNull NewsSourceDto source);

}



public interface SourcesView extends MVPView {



void setSources(@NonNull List<NewsSourceDto> sources);



void setProgressVisible(boolean visible);



void showError(@NonNull String errorMessage);

}

}
final class SourcesPresenter extends BasePresenter<SourcesContract.View>

implements SourcesContract.Presenter {



@Inject

SourcesPresenter(@NonNull Lazy<SourcesContract.Starter> starter,

@NonNull NewsSourcesDataSource dataSource,

@NonNull @Named(RxModule.COMPUTATION) Scheduler computationScheduler,

@NonNull @Named(RxModule.MAIN) Scheduler observerScheduler) {
…

}
}
public final class NewsSourcesDataSource {



@Inject

public NewsSourcesDataSource(@NonNull NewsSourcesRestService service,
@NonNull @Named(RxModule.NETWORK) Scheduler networkScheduler) {
…
}
…
}
public final class NewsSourcesDataSource {



@Inject

public NewsSourcesDataSource(@NonNull NewsSourcesRestService service,
@NonNull @Named(RxModule.NETWORK) Scheduler networkScheduler) {
…
}
…
}
public interface NewsSourcesRestService {



@NonNull

@GET("sources")

Single<NewsSourcesResponseDto> sources();

}
Unit Тесты
Что используется
Зависимости
testCompile 'org.mockito:mockito-core:2.8.9'

testCompile 'junit:junit:4.12'
@RunWith(MockitoJUnitRunner.class)

public class SourcesPresenterTest {



@Mock SourcesContract.Starter mMockStarter;



@Mock SourcesContract.View mMockView;



@Mock NewsSourcesRestService mMockRestService;



private SourcesPresenter mSourcesPresenter;



@Before

public void init() {

Scheduler testScheduler = …;



Lazy<SourcesContract.Starter> starter = () -> mMockStarter;

NewsSourcesDataSource dataSource =

new NewsSourcesDataSource(mMockRestService, testScheduler);


mSourcesPresenter = new SourcesPresenter(

starter, dataSource, testScheduler, testScheduler);

}

}
@Test

public void test() {
doAnswer(invocation -> Single.just(newNewsSourceDataResponse()))

.when(mMockRestService)
.sources();


mSourcesPresenter.attachView(mMockView);



verify(mMockView, times(1)).setProgressVisible(true);

verify(mMockRestService, times(1)).sources();



verify(mMockView, times(1)).setSources(any());

verify(mMockView, times(1)).setProgressVisible(false);



mSourcesPresenter.onDetachView();

mSourcesPresenter.onDestroyView();

}
Тестирование
компонентов Android SDK
Что используется
Зависимости
testCompile “org.mockito:mockito-core:2.8.9“

testCompile 'junit:junit:4.12'

testCompile "org.robolectric:robolectric:3.3.2"
@RunWith(RobolectricTestRunner.class)

@Config(sdk = Build.VERSION_CODES.LOLLIPOP, constants = BuildConfig.class)

public class SourcesActivityTest {



private SourcesActivity mSourcesActivity;



@Before

public void setup() {
mSourcesActivity = Robolectric.setupActivity(SourcesActivity.class);
}



@Test

public void test() throws Exception {

final View progressView =
mSourcesActivity.findViewById(R.id.progress);

assertThat(progressView.getVisibility(), equalTo(View.GONE));



final RecyclerView sourcesView =
(RecyclerView) mSourcesActivity.findViewById(R.id.list);

assertThat(sourcesView.getVisibility(), equalTo(View.VISIBLE));



final SourceAdapter adapter =
(SourceAdapter) sourcesView.getAdapter();

assertThat(adapter, notNullValue());

assertThat(adapter.getItemCount(), equalTo(1));

final NewsSourceDto source = adapter.getItem(0);

assertThat(source,
equalTo(newNewsSourceDataResponse().getSources().get(0)));



final View sourceView = sourcesView.getChildAt(0);

final TextView sourceNameView =
(TextView) sourceView.findViewById(R.id.name);

assertThat(sourceNameView.getText(), equalTo(source.getName()));

assertThat(sourceNameView.getVisibility(), equalTo(View.VISIBLE));

}

}
Проблемы
1.Необходимо сделать тесты синхронными
2.Необходимо заменить получение данных с
сервера на стабовые
Product Flavors
android {



flavorDimensions ‘mode'


productFlavors {

common {

dimension = 'mode'

}



mock {

dimension = 'mode'

}

}

}
Зависимости
mockCompile “org.mockito:mockito-core:2.8.9“


testCompile 'junit:junit:4.12'

testCompile "org.robolectric:robolectric:3.3.2"
android {



flavorDimensions ‘mode'

productFlavors {

common { dimension = 'mode'}

mock { dimension = 'mode'}

}



variantFilter { variant ->

if (variant.buildType.name != 'debug') {

def names = variant.flavors*.name

if (names.contains('mock')) {

setIgnore(true)

}

}

}

}
Product Flavors
app/src/main/java/com/kirich1409/news/dagger/RxModule.java
app/src/common/java/com/kirich1409/news/dagger/RxModule.java
app/src/mock/java/com/kirich1409/news/dagger/RxModule.java
Mock RxModule
@Module

public abstract class RxModule {



public static final String NETWORK = “network”,
MAIN = “main”,
COMPUTATION = “computation";


@Provides @Named(COMPUTATION)

public static Scheduler provideComputationScheduler() {

return Schedulers.computation();

}



@Provides @Named(NETWORK)

public static Scheduler provideNetworkScheduler() {

return Schedulers.computation();

}



@Provides @Named(MAIN)

public static Scheduler provideMainScheduler() {

return AndroidSchedulers.mainThread();

}

}
Mock NewsApiModule
@Module(includes = NewsNetworkModule.class)

public abstract class NewsApiModule {



@Singleton @Provides

static ArticlesRestService provideArticlesRestService() {

ArticlesRestService mock = Mockito.mock(ArticlesRestService.class);

ArticlesResponseDto responseDto = new ArticlesResponseDto(STATUS_ERROR, "", emptyList(), SORT_LATEST, 0, "");

Mockito.when(mock.articles(anyString(), isNull())).thenReturn(Single.just(responseDto));

return mock;

}



public static NewsSourcesResponseDto newNewsSourceDataResponse() {

NewsSourceDto newsSourceDto = new NewsSourceDto(

"sample_id","Sample news","Sample new for Unit test”, "http://www.sample.org/item.html");

return new NewsSourcesResponseDto(STATUS_OK, singletonList(newsSourceDto), 0, "");

}



@Singleton @Provides

static NewsSourcesRestService provideNewsSourcesRestService() {

NewsSourcesRestService mock = Mockito.mock(NewsSourcesRestService.class);

Mockito.when(mock.sources()).thenReturn(Single.just(newNewsSourceDataResponse()));

return mock;

}

}
Instrumentation тесты
Что используется
Зависимости
mockCompile “org.mockito:mockito-core:2.8.9“
androidTestCompile “org.mockito:mockito-android:2.8.9”

androidTestCompile “com.android.support.test.espresso:espresso-core:2.2.2”
Настройка сборки
android {



defaultConfig {


testInstrumentationRunner 'android.support.test.runner.AndroidJUnitRunner'



}

}
@RunWith(AndroidJUnit4.class) @LargeTest

public class SourceActivityTest {



@Rule

public IntentsTestRule<SourcesActivity> mActivityRule = new IntentsTestRule<>(SourcesActivity.class);



@Test

public void test() throws Exception {

onView(withId(R.id.list))

.check(matches(childCount(1)))

.check(matches(hasDescendant(withId(R.id.name))));



NewsSourcesResponseDto responseDto = NewsApiModule.newNewsSourceDataResponse();

onView(withId(R.id.name))

.check(matches(withText(responseDto.getSources().get(0).getName())));



onView(withId(R.id.list))

.perform(actionOnItemAtPosition(0, click()));



ComponentName articlesActivity =

new ComponentName(mActivityRule.getActivity(), ArticlesActivity.class);

intended(hasComponent(articlesActivity));

}

}
Espresso
• Core
• Contrib
• Idling Resources
• Intents
• Web
Материалы
• JUnit4
• Mockito
• Basic Guide
• Robolectric
• Android:Getting Started with Testing
• Android Testing Support Library
• Android Espresso
• Android Testing Codelab
Спасибо за внимание

More Related Content

What's hot

React, Redux and es6/7
React, Redux and es6/7React, Redux and es6/7
React, Redux and es6/7Dongho Cho
 
Java(8) The Good, The Bad and the Ugly
Java(8) The Good, The Bad and the UglyJava(8) The Good, The Bad and the Ugly
Java(8) The Good, The Bad and the UglyBrian Vermeer
 
Android Design Patterns
Android Design PatternsAndroid Design Patterns
Android Design PatternsGodfrey Nolan
 
Spring 4 advanced final_xtr_presentation
Spring 4 advanced final_xtr_presentationSpring 4 advanced final_xtr_presentation
Spring 4 advanced final_xtr_presentationsourabh aggarwal
 
Java8 tgtbatu javaone
Java8 tgtbatu javaoneJava8 tgtbatu javaone
Java8 tgtbatu javaoneBrian Vermeer
 
Dagger 2. The Right Way to Dependency Injections
Dagger 2. The Right Way to Dependency InjectionsDagger 2. The Right Way to Dependency Injections
Dagger 2. The Right Way to Dependency InjectionsGlobalLogic Ukraine
 
Dagger 2. Right way to do Dependency Injection
Dagger 2. Right way to do Dependency InjectionDagger 2. Right way to do Dependency Injection
Dagger 2. Right way to do Dependency InjectionStfalcon Meetups
 
Advanced Dagger talk from 360andev
Advanced Dagger talk from 360andevAdvanced Dagger talk from 360andev
Advanced Dagger talk from 360andevMike Nakhimovich
 
知っておきたいSpring Batch Tips
知っておきたいSpring Batch Tips知っておきたいSpring Batch Tips
知っておきたいSpring Batch Tipsikeyat
 
Testing Android apps based on Dagger and RxJava
Testing Android apps based on Dagger and RxJavaTesting Android apps based on Dagger and RxJava
Testing Android apps based on Dagger and RxJavaFabio Collini
 
Quick start with React | DreamLab Academy #2
Quick start with React | DreamLab Academy #2Quick start with React | DreamLab Academy #2
Quick start with React | DreamLab Academy #2DreamLab
 
Intro to Retrofit 2 and RxJava2
Intro to Retrofit 2 and RxJava2Intro to Retrofit 2 and RxJava2
Intro to Retrofit 2 and RxJava2Fabio Collini
 
Android Best Practices
Android Best PracticesAndroid Best Practices
Android Best PracticesYekmer Simsek
 
Redux for ReactJS Programmers
Redux for ReactJS ProgrammersRedux for ReactJS Programmers
Redux for ReactJS ProgrammersDavid Rodenas
 
Retrofit Technology Overview by Cumulations Technologies
Retrofit Technology Overview by Cumulations TechnologiesRetrofit Technology Overview by Cumulations Technologies
Retrofit Technology Overview by Cumulations TechnologiesCumulations Technologies
 

What's hot (20)

React, Redux and es6/7
React, Redux and es6/7React, Redux and es6/7
React, Redux and es6/7
 
Java(8) The Good, The Bad and the Ugly
Java(8) The Good, The Bad and the UglyJava(8) The Good, The Bad and the Ugly
Java(8) The Good, The Bad and the Ugly
 
React lecture
React lectureReact lecture
React lecture
 
Android Design Patterns
Android Design PatternsAndroid Design Patterns
Android Design Patterns
 
Spring 4 advanced final_xtr_presentation
Spring 4 advanced final_xtr_presentationSpring 4 advanced final_xtr_presentation
Spring 4 advanced final_xtr_presentation
 
Java8 tgtbatu javaone
Java8 tgtbatu javaoneJava8 tgtbatu javaone
Java8 tgtbatu javaone
 
Android TDD
Android TDDAndroid TDD
Android TDD
 
Dagger 2. The Right Way to Dependency Injections
Dagger 2. The Right Way to Dependency InjectionsDagger 2. The Right Way to Dependency Injections
Dagger 2. The Right Way to Dependency Injections
 
Dagger 2. Right way to do Dependency Injection
Dagger 2. Right way to do Dependency InjectionDagger 2. Right way to do Dependency Injection
Dagger 2. Right way to do Dependency Injection
 
Advanced Dagger talk from 360andev
Advanced Dagger talk from 360andevAdvanced Dagger talk from 360andev
Advanced Dagger talk from 360andev
 
droidparts
droidpartsdroidparts
droidparts
 
知っておきたいSpring Batch Tips
知っておきたいSpring Batch Tips知っておきたいSpring Batch Tips
知っておきたいSpring Batch Tips
 
Testing Android apps based on Dagger and RxJava
Testing Android apps based on Dagger and RxJavaTesting Android apps based on Dagger and RxJava
Testing Android apps based on Dagger and RxJava
 
Angular 2 introduction
Angular 2 introductionAngular 2 introduction
Angular 2 introduction
 
Quick start with React | DreamLab Academy #2
Quick start with React | DreamLab Academy #2Quick start with React | DreamLab Academy #2
Quick start with React | DreamLab Academy #2
 
Intro to Retrofit 2 and RxJava2
Intro to Retrofit 2 and RxJava2Intro to Retrofit 2 and RxJava2
Intro to Retrofit 2 and RxJava2
 
Annotation processing
Annotation processingAnnotation processing
Annotation processing
 
Android Best Practices
Android Best PracticesAndroid Best Practices
Android Best Practices
 
Redux for ReactJS Programmers
Redux for ReactJS ProgrammersRedux for ReactJS Programmers
Redux for ReactJS Programmers
 
Retrofit Technology Overview by Cumulations Technologies
Retrofit Technology Overview by Cumulations TechnologiesRetrofit Technology Overview by Cumulations Technologies
Retrofit Technology Overview by Cumulations Technologies
 

Similar to Dagger 2 testing on Android

Guide to the jungle of testing frameworks
Guide to the jungle of testing frameworksGuide to the jungle of testing frameworks
Guide to the jungle of testing frameworksTomáš Kypta
 
Adding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsAdding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsJeff Durta
 
Dev fest kyoto_2021-flutter_test
Dev fest kyoto_2021-flutter_testDev fest kyoto_2021-flutter_test
Dev fest kyoto_2021-flutter_testMasanori Kato
 
Hacking the Codename One Source Code - Part IV - Transcript.pdf
Hacking the Codename One Source Code - Part IV - Transcript.pdfHacking the Codename One Source Code - Part IV - Transcript.pdf
Hacking the Codename One Source Code - Part IV - Transcript.pdfShaiAlmog1
 
Workshop 26: React Native - The Native Side
Workshop 26: React Native - The Native SideWorkshop 26: React Native - The Native Side
Workshop 26: React Native - The Native SideVisual Engineering
 
From Legacy to Hexagonal (An Unexpected Android Journey)
From Legacy to Hexagonal (An Unexpected Android Journey)From Legacy to Hexagonal (An Unexpected Android Journey)
From Legacy to Hexagonal (An Unexpected Android Journey)Jose Manuel Pereira Garcia
 
The real beginner's guide to android testing
The real beginner's guide to android testingThe real beginner's guide to android testing
The real beginner's guide to android testingEric (Trung Dung) Nguyen
 
Testing your application on Google App Engine
Testing your application on Google App EngineTesting your application on Google App Engine
Testing your application on Google App EngineInphina Technologies
 
Testing Your Application On Google App Engine
Testing Your Application On Google App EngineTesting Your Application On Google App Engine
Testing Your Application On Google App EngineIndicThreads
 
Unit Testing on Android - Droidcon Berlin 2015
Unit Testing on Android - Droidcon Berlin 2015Unit Testing on Android - Droidcon Berlin 2015
Unit Testing on Android - Droidcon Berlin 2015Buşra Deniz, CSM
 
Test strategy for web development
Test strategy for web developmentTest strategy for web development
Test strategy for web developmentalice yang
 
Building Modern Apps using Android Architecture Components
Building Modern Apps using Android Architecture ComponentsBuilding Modern Apps using Android Architecture Components
Building Modern Apps using Android Architecture ComponentsHassan Abid
 
Workshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testingWorkshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testingVisual Engineering
 
Developing ASP.NET Applications Using the Model View Controller Pattern
Developing ASP.NET Applications Using the Model View Controller PatternDeveloping ASP.NET Applications Using the Model View Controller Pattern
Developing ASP.NET Applications Using the Model View Controller Patterngoodfriday
 
Android Unit Test
Android Unit TestAndroid Unit Test
Android Unit TestPhuoc Bui
 
How to code to code less
How to code to code lessHow to code to code less
How to code to code lessAnton Novikau
 
Testing android apps with espresso
Testing android apps with espressoTesting android apps with espresso
Testing android apps with espressoÉdipo Souza
 
Ember.js - A JavaScript framework for creating ambitious web applications
Ember.js - A JavaScript framework for creating ambitious web applications  Ember.js - A JavaScript framework for creating ambitious web applications
Ember.js - A JavaScript framework for creating ambitious web applications Juliana Lucena
 

Similar to Dagger 2 testing on Android (20)

Guide to the jungle of testing frameworks
Guide to the jungle of testing frameworksGuide to the jungle of testing frameworks
Guide to the jungle of testing frameworks
 
Adding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsAdding a modern twist to legacy web applications
Adding a modern twist to legacy web applications
 
Dev fest kyoto_2021-flutter_test
Dev fest kyoto_2021-flutter_testDev fest kyoto_2021-flutter_test
Dev fest kyoto_2021-flutter_test
 
Hacking the Codename One Source Code - Part IV - Transcript.pdf
Hacking the Codename One Source Code - Part IV - Transcript.pdfHacking the Codename One Source Code - Part IV - Transcript.pdf
Hacking the Codename One Source Code - Part IV - Transcript.pdf
 
Workshop 26: React Native - The Native Side
Workshop 26: React Native - The Native SideWorkshop 26: React Native - The Native Side
Workshop 26: React Native - The Native Side
 
From Legacy to Hexagonal (An Unexpected Android Journey)
From Legacy to Hexagonal (An Unexpected Android Journey)From Legacy to Hexagonal (An Unexpected Android Journey)
From Legacy to Hexagonal (An Unexpected Android Journey)
 
The real beginner's guide to android testing
The real beginner's guide to android testingThe real beginner's guide to android testing
The real beginner's guide to android testing
 
Testing your application on Google App Engine
Testing your application on Google App EngineTesting your application on Google App Engine
Testing your application on Google App Engine
 
Testing Your Application On Google App Engine
Testing Your Application On Google App EngineTesting Your Application On Google App Engine
Testing Your Application On Google App Engine
 
Unit Testing on Android - Droidcon Berlin 2015
Unit Testing on Android - Droidcon Berlin 2015Unit Testing on Android - Droidcon Berlin 2015
Unit Testing on Android - Droidcon Berlin 2015
 
Lesson 2
Lesson 2Lesson 2
Lesson 2
 
Test strategy for web development
Test strategy for web developmentTest strategy for web development
Test strategy for web development
 
Spring boot
Spring boot Spring boot
Spring boot
 
Building Modern Apps using Android Architecture Components
Building Modern Apps using Android Architecture ComponentsBuilding Modern Apps using Android Architecture Components
Building Modern Apps using Android Architecture Components
 
Workshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testingWorkshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testing
 
Developing ASP.NET Applications Using the Model View Controller Pattern
Developing ASP.NET Applications Using the Model View Controller PatternDeveloping ASP.NET Applications Using the Model View Controller Pattern
Developing ASP.NET Applications Using the Model View Controller Pattern
 
Android Unit Test
Android Unit TestAndroid Unit Test
Android Unit Test
 
How to code to code less
How to code to code lessHow to code to code less
How to code to code less
 
Testing android apps with espresso
Testing android apps with espressoTesting android apps with espresso
Testing android apps with espresso
 
Ember.js - A JavaScript framework for creating ambitious web applications
Ember.js - A JavaScript framework for creating ambitious web applications  Ember.js - A JavaScript framework for creating ambitious web applications
Ember.js - A JavaScript framework for creating ambitious web applications
 

More from Kirill Rozov

Kotlin Coroutines. Flow is coming
Kotlin Coroutines. Flow is comingKotlin Coroutines. Flow is coming
Kotlin Coroutines. Flow is comingKirill Rozov
 
2 years without Java. Kotlin only
2 years without Java. Kotlin only2 years without Java. Kotlin only
2 years without Java. Kotlin onlyKirill Rozov
 
Почему Kotlin?
Почему Kotlin?Почему Kotlin?
Почему Kotlin?Kirill Rozov
 
KOIN for dependency Injection
KOIN for dependency InjectionKOIN for dependency Injection
KOIN for dependency InjectionKirill Rozov
 
ConstraintLayout. Fell the Power of constraints
ConstraintLayout. Fell the Power of constraintsConstraintLayout. Fell the Power of constraints
ConstraintLayout. Fell the Power of constraintsKirill Rozov
 
Kotlin 1.2: Sharing code between platforms
Kotlin 1.2: Sharing code between platformsKotlin 1.2: Sharing code between platforms
Kotlin 1.2: Sharing code between platformsKirill Rozov
 
Kotlin - следующий язык после Java
Kotlin - следующий язык после JavaKotlin - следующий язык после Java
Kotlin - следующий язык после JavaKirill Rozov
 
Kotlin Advanced - Apalon Kotlin Sprint Part 3
Kotlin Advanced - Apalon Kotlin Sprint Part 3Kotlin Advanced - Apalon Kotlin Sprint Part 3
Kotlin Advanced - Apalon Kotlin Sprint Part 3Kirill Rozov
 
Kotlin Basics - Apalon Kotlin Sprint Part 2
Kotlin Basics - Apalon Kotlin Sprint Part 2Kotlin Basics - Apalon Kotlin Sprint Part 2
Kotlin Basics - Apalon Kotlin Sprint Part 2Kirill Rozov
 
Что нового в Android O (Grodno HTP)
Что нового в Android O (Grodno HTP)Что нового в Android O (Grodno HTP)
Что нового в Android O (Grodno HTP)Kirill Rozov
 
Gradle Introduction
Gradle IntroductionGradle Introduction
Gradle IntroductionKirill Rozov
 
Kotlin для Android
Kotlin для AndroidKotlin для Android
Kotlin для AndroidKirill Rozov
 
What's new in Android M
What's new in Android MWhat's new in Android M
What's new in Android MKirill Rozov
 
Android Data Binding
Android Data BindingAndroid Data Binding
Android Data BindingKirill Rozov
 

More from Kirill Rozov (19)

Kotlin Coroutines. Flow is coming
Kotlin Coroutines. Flow is comingKotlin Coroutines. Flow is coming
Kotlin Coroutines. Flow is coming
 
2 years without Java. Kotlin only
2 years without Java. Kotlin only2 years without Java. Kotlin only
2 years without Java. Kotlin only
 
Почему Kotlin?
Почему Kotlin?Почему Kotlin?
Почему Kotlin?
 
KOIN for dependency Injection
KOIN for dependency InjectionKOIN for dependency Injection
KOIN for dependency Injection
 
Optimize APK size
Optimize APK sizeOptimize APK size
Optimize APK size
 
ConstraintLayout. Fell the Power of constraints
ConstraintLayout. Fell the Power of constraintsConstraintLayout. Fell the Power of constraints
ConstraintLayout. Fell the Power of constraints
 
Kotlin 1.2: Sharing code between platforms
Kotlin 1.2: Sharing code between platformsKotlin 1.2: Sharing code between platforms
Kotlin 1.2: Sharing code between platforms
 
Kotlin - следующий язык после Java
Kotlin - следующий язык после JavaKotlin - следующий язык после Java
Kotlin - следующий язык после Java
 
Kotlin Advanced - Apalon Kotlin Sprint Part 3
Kotlin Advanced - Apalon Kotlin Sprint Part 3Kotlin Advanced - Apalon Kotlin Sprint Part 3
Kotlin Advanced - Apalon Kotlin Sprint Part 3
 
Kotlin Basics - Apalon Kotlin Sprint Part 2
Kotlin Basics - Apalon Kotlin Sprint Part 2Kotlin Basics - Apalon Kotlin Sprint Part 2
Kotlin Basics - Apalon Kotlin Sprint Part 2
 
Что нового в Android O (Grodno HTP)
Что нового в Android O (Grodno HTP)Что нового в Android O (Grodno HTP)
Что нового в Android O (Grodno HTP)
 
Android service
Android serviceAndroid service
Android service
 
Effective Java
Effective JavaEffective Java
Effective Java
 
Dagger 2
Dagger 2Dagger 2
Dagger 2
 
Gradle Introduction
Gradle IntroductionGradle Introduction
Gradle Introduction
 
REST
RESTREST
REST
 
Kotlin для Android
Kotlin для AndroidKotlin для Android
Kotlin для Android
 
What's new in Android M
What's new in Android MWhat's new in Android M
What's new in Android M
 
Android Data Binding
Android Data BindingAndroid Data Binding
Android Data Binding
 

Recently uploaded

9892124323 | Book Call Girls in Juhu and escort services 24x7
9892124323 | Book Call Girls in Juhu and escort services 24x79892124323 | Book Call Girls in Juhu and escort services 24x7
9892124323 | Book Call Girls in Juhu and escort services 24x7Pooja Nehwal
 
Chandigarh Call Girls Service ❤️🍑 9115573837 👄🫦Independent Escort Service Cha...
Chandigarh Call Girls Service ❤️🍑 9115573837 👄🫦Independent Escort Service Cha...Chandigarh Call Girls Service ❤️🍑 9115573837 👄🫦Independent Escort Service Cha...
Chandigarh Call Girls Service ❤️🍑 9115573837 👄🫦Independent Escort Service Cha...Niamh verma
 
BDSM⚡Call Girls in Sector 71 Noida Escorts >༒8448380779 Escort Service
BDSM⚡Call Girls in Sector 71 Noida Escorts >༒8448380779 Escort ServiceBDSM⚡Call Girls in Sector 71 Noida Escorts >༒8448380779 Escort Service
BDSM⚡Call Girls in Sector 71 Noida Escorts >༒8448380779 Escort ServiceDelhi Call girls
 
CALL ON ➥8923113531 🔝Call Girls Saharaganj Lucknow best sexual service
CALL ON ➥8923113531 🔝Call Girls Saharaganj Lucknow best sexual serviceCALL ON ➥8923113531 🔝Call Girls Saharaganj Lucknow best sexual service
CALL ON ➥8923113531 🔝Call Girls Saharaganj Lucknow best sexual serviceanilsa9823
 
CALL ON ➥8923113531 🔝Call Girls Gomti Nagar Lucknow best Night Fun service
CALL ON ➥8923113531 🔝Call Girls Gomti Nagar Lucknow best Night Fun serviceCALL ON ➥8923113531 🔝Call Girls Gomti Nagar Lucknow best Night Fun service
CALL ON ➥8923113531 🔝Call Girls Gomti Nagar Lucknow best Night Fun serviceanilsa9823
 
哪里有卖的《俄亥俄大学学历证书+俄亥俄大学文凭证书+俄亥俄大学学位证书》Q微信741003700《俄亥俄大学学位证书复制》办理俄亥俄大学毕业证成绩单|购买...
哪里有卖的《俄亥俄大学学历证书+俄亥俄大学文凭证书+俄亥俄大学学位证书》Q微信741003700《俄亥俄大学学位证书复制》办理俄亥俄大学毕业证成绩单|购买...哪里有卖的《俄亥俄大学学历证书+俄亥俄大学文凭证书+俄亥俄大学学位证书》Q微信741003700《俄亥俄大学学位证书复制》办理俄亥俄大学毕业证成绩单|购买...
哪里有卖的《俄亥俄大学学历证书+俄亥俄大学文凭证书+俄亥俄大学学位证书》Q微信741003700《俄亥俄大学学位证书复制》办理俄亥俄大学毕业证成绩单|购买...wyqazy
 
Call US Pooja 9892124323 ✓Call Girls In Mira Road ( Mumbai ) secure service,
Call US Pooja 9892124323 ✓Call Girls In Mira Road ( Mumbai ) secure service,Call US Pooja 9892124323 ✓Call Girls In Mira Road ( Mumbai ) secure service,
Call US Pooja 9892124323 ✓Call Girls In Mira Road ( Mumbai ) secure service,Pooja Nehwal
 
Powerful Love Spells in Arkansas, AR (310) 882-6330 Bring Back Lost Lover
Powerful Love Spells in Arkansas, AR (310) 882-6330 Bring Back Lost LoverPowerful Love Spells in Arkansas, AR (310) 882-6330 Bring Back Lost Lover
Powerful Love Spells in Arkansas, AR (310) 882-6330 Bring Back Lost LoverPsychicRuben LoveSpells
 
FULL ENJOY - 9999218229 Call Girls in {Mahipalpur}| Delhi NCR
FULL ENJOY - 9999218229 Call Girls in {Mahipalpur}| Delhi NCRFULL ENJOY - 9999218229 Call Girls in {Mahipalpur}| Delhi NCR
FULL ENJOY - 9999218229 Call Girls in {Mahipalpur}| Delhi NCRnishacall1
 

Recently uploaded (9)

9892124323 | Book Call Girls in Juhu and escort services 24x7
9892124323 | Book Call Girls in Juhu and escort services 24x79892124323 | Book Call Girls in Juhu and escort services 24x7
9892124323 | Book Call Girls in Juhu and escort services 24x7
 
Chandigarh Call Girls Service ❤️🍑 9115573837 👄🫦Independent Escort Service Cha...
Chandigarh Call Girls Service ❤️🍑 9115573837 👄🫦Independent Escort Service Cha...Chandigarh Call Girls Service ❤️🍑 9115573837 👄🫦Independent Escort Service Cha...
Chandigarh Call Girls Service ❤️🍑 9115573837 👄🫦Independent Escort Service Cha...
 
BDSM⚡Call Girls in Sector 71 Noida Escorts >༒8448380779 Escort Service
BDSM⚡Call Girls in Sector 71 Noida Escorts >༒8448380779 Escort ServiceBDSM⚡Call Girls in Sector 71 Noida Escorts >༒8448380779 Escort Service
BDSM⚡Call Girls in Sector 71 Noida Escorts >༒8448380779 Escort Service
 
CALL ON ➥8923113531 🔝Call Girls Saharaganj Lucknow best sexual service
CALL ON ➥8923113531 🔝Call Girls Saharaganj Lucknow best sexual serviceCALL ON ➥8923113531 🔝Call Girls Saharaganj Lucknow best sexual service
CALL ON ➥8923113531 🔝Call Girls Saharaganj Lucknow best sexual service
 
CALL ON ➥8923113531 🔝Call Girls Gomti Nagar Lucknow best Night Fun service
CALL ON ➥8923113531 🔝Call Girls Gomti Nagar Lucknow best Night Fun serviceCALL ON ➥8923113531 🔝Call Girls Gomti Nagar Lucknow best Night Fun service
CALL ON ➥8923113531 🔝Call Girls Gomti Nagar Lucknow best Night Fun service
 
哪里有卖的《俄亥俄大学学历证书+俄亥俄大学文凭证书+俄亥俄大学学位证书》Q微信741003700《俄亥俄大学学位证书复制》办理俄亥俄大学毕业证成绩单|购买...
哪里有卖的《俄亥俄大学学历证书+俄亥俄大学文凭证书+俄亥俄大学学位证书》Q微信741003700《俄亥俄大学学位证书复制》办理俄亥俄大学毕业证成绩单|购买...哪里有卖的《俄亥俄大学学历证书+俄亥俄大学文凭证书+俄亥俄大学学位证书》Q微信741003700《俄亥俄大学学位证书复制》办理俄亥俄大学毕业证成绩单|购买...
哪里有卖的《俄亥俄大学学历证书+俄亥俄大学文凭证书+俄亥俄大学学位证书》Q微信741003700《俄亥俄大学学位证书复制》办理俄亥俄大学毕业证成绩单|购买...
 
Call US Pooja 9892124323 ✓Call Girls In Mira Road ( Mumbai ) secure service,
Call US Pooja 9892124323 ✓Call Girls In Mira Road ( Mumbai ) secure service,Call US Pooja 9892124323 ✓Call Girls In Mira Road ( Mumbai ) secure service,
Call US Pooja 9892124323 ✓Call Girls In Mira Road ( Mumbai ) secure service,
 
Powerful Love Spells in Arkansas, AR (310) 882-6330 Bring Back Lost Lover
Powerful Love Spells in Arkansas, AR (310) 882-6330 Bring Back Lost LoverPowerful Love Spells in Arkansas, AR (310) 882-6330 Bring Back Lost Lover
Powerful Love Spells in Arkansas, AR (310) 882-6330 Bring Back Lost Lover
 
FULL ENJOY - 9999218229 Call Girls in {Mahipalpur}| Delhi NCR
FULL ENJOY - 9999218229 Call Girls in {Mahipalpur}| Delhi NCRFULL ENJOY - 9999218229 Call Girls in {Mahipalpur}| Delhi NCR
FULL ENJOY - 9999218229 Call Girls in {Mahipalpur}| Delhi NCR
 

Dagger 2 testing on Android

  • 2. Виды тестирования • Простые Unit тесты • Тестирование Android компонентов • Instrumentation тесты
  • 3. public final class SourcesContract {
 
 public interface Presenter extends MVPPresenter<SourcesView> {
 
 void openArticles(final @NonNull NewsSourceDto source);
 }
 
 public interface Starter {
 
 void openArticles(final @NonNull NewsSourceDto source);
 }
 
 public interface SourcesView extends MVPView {
 
 void setSources(@NonNull List<NewsSourceDto> sources);
 
 void setProgressVisible(boolean visible);
 
 void showError(@NonNull String errorMessage);
 }
 }
  • 4. final class SourcesPresenter extends BasePresenter<SourcesContract.View>
 implements SourcesContract.Presenter {
 
 @Inject
 SourcesPresenter(@NonNull Lazy<SourcesContract.Starter> starter,
 @NonNull NewsSourcesDataSource dataSource,
 @NonNull @Named(RxModule.COMPUTATION) Scheduler computationScheduler,
 @NonNull @Named(RxModule.MAIN) Scheduler observerScheduler) { …
 } }
  • 5. public final class NewsSourcesDataSource {
 
 @Inject
 public NewsSourcesDataSource(@NonNull NewsSourcesRestService service, @NonNull @Named(RxModule.NETWORK) Scheduler networkScheduler) { … } … }
  • 6. public final class NewsSourcesDataSource {
 
 @Inject
 public NewsSourcesDataSource(@NonNull NewsSourcesRestService service, @NonNull @Named(RxModule.NETWORK) Scheduler networkScheduler) { … } … } public interface NewsSourcesRestService {
 
 @NonNull
 @GET("sources")
 Single<NewsSourcesResponseDto> sources();
 }
  • 10. @RunWith(MockitoJUnitRunner.class)
 public class SourcesPresenterTest {
 
 @Mock SourcesContract.Starter mMockStarter;
 
 @Mock SourcesContract.View mMockView;
 
 @Mock NewsSourcesRestService mMockRestService;
 
 private SourcesPresenter mSourcesPresenter;
 
 @Before
 public void init() {
 Scheduler testScheduler = …;
 
 Lazy<SourcesContract.Starter> starter = () -> mMockStarter;
 NewsSourcesDataSource dataSource =
 new NewsSourcesDataSource(mMockRestService, testScheduler); 
 mSourcesPresenter = new SourcesPresenter(
 starter, dataSource, testScheduler, testScheduler);
 }
 }
  • 11. @Test
 public void test() { doAnswer(invocation -> Single.just(newNewsSourceDataResponse()))
 .when(mMockRestService) .sources(); 
 mSourcesPresenter.attachView(mMockView);
 
 verify(mMockView, times(1)).setProgressVisible(true);
 verify(mMockRestService, times(1)).sources();
 
 verify(mMockView, times(1)).setSources(any());
 verify(mMockView, times(1)).setProgressVisible(false);
 
 mSourcesPresenter.onDetachView();
 mSourcesPresenter.onDestroyView();
 }
  • 15. @RunWith(RobolectricTestRunner.class)
 @Config(sdk = Build.VERSION_CODES.LOLLIPOP, constants = BuildConfig.class)
 public class SourcesActivityTest {
 
 private SourcesActivity mSourcesActivity;
 
 @Before
 public void setup() { mSourcesActivity = Robolectric.setupActivity(SourcesActivity.class); }
 
 @Test
 public void test() throws Exception {
 final View progressView = mSourcesActivity.findViewById(R.id.progress);
 assertThat(progressView.getVisibility(), equalTo(View.GONE));
 
 final RecyclerView sourcesView = (RecyclerView) mSourcesActivity.findViewById(R.id.list);
 assertThat(sourcesView.getVisibility(), equalTo(View.VISIBLE));
 
 final SourceAdapter adapter = (SourceAdapter) sourcesView.getAdapter();
 assertThat(adapter, notNullValue());
 assertThat(adapter.getItemCount(), equalTo(1));
 final NewsSourceDto source = adapter.getItem(0);
 assertThat(source, equalTo(newNewsSourceDataResponse().getSources().get(0)));
 
 final View sourceView = sourcesView.getChildAt(0);
 final TextView sourceNameView = (TextView) sourceView.findViewById(R.id.name);
 assertThat(sourceNameView.getText(), equalTo(source.getName()));
 assertThat(sourceNameView.getVisibility(), equalTo(View.VISIBLE));
 }
 }
  • 16. Проблемы 1.Необходимо сделать тесты синхронными 2.Необходимо заменить получение данных с сервера на стабовые
  • 17. Product Flavors android {
 
 flavorDimensions ‘mode' 
 productFlavors {
 common {
 dimension = 'mode'
 }
 
 mock {
 dimension = 'mode'
 }
 }
 }
  • 19. android {
 
 flavorDimensions ‘mode'
 productFlavors {
 common { dimension = 'mode'}
 mock { dimension = 'mode'}
 }
 
 variantFilter { variant ->
 if (variant.buildType.name != 'debug') {
 def names = variant.flavors*.name
 if (names.contains('mock')) {
 setIgnore(true)
 }
 }
 }
 } Product Flavors
  • 22. Mock RxModule @Module
 public abstract class RxModule {
 
 public static final String NETWORK = “network”, MAIN = “main”, COMPUTATION = “computation"; 
 @Provides @Named(COMPUTATION)
 public static Scheduler provideComputationScheduler() {
 return Schedulers.computation();
 }
 
 @Provides @Named(NETWORK)
 public static Scheduler provideNetworkScheduler() {
 return Schedulers.computation();
 }
 
 @Provides @Named(MAIN)
 public static Scheduler provideMainScheduler() {
 return AndroidSchedulers.mainThread();
 }
 }
  • 23. Mock NewsApiModule @Module(includes = NewsNetworkModule.class)
 public abstract class NewsApiModule {
 
 @Singleton @Provides
 static ArticlesRestService provideArticlesRestService() {
 ArticlesRestService mock = Mockito.mock(ArticlesRestService.class);
 ArticlesResponseDto responseDto = new ArticlesResponseDto(STATUS_ERROR, "", emptyList(), SORT_LATEST, 0, "");
 Mockito.when(mock.articles(anyString(), isNull())).thenReturn(Single.just(responseDto));
 return mock;
 }
 
 public static NewsSourcesResponseDto newNewsSourceDataResponse() {
 NewsSourceDto newsSourceDto = new NewsSourceDto(
 "sample_id","Sample news","Sample new for Unit test”, "http://www.sample.org/item.html");
 return new NewsSourcesResponseDto(STATUS_OK, singletonList(newsSourceDto), 0, "");
 }
 
 @Singleton @Provides
 static NewsSourcesRestService provideNewsSourcesRestService() {
 NewsSourcesRestService mock = Mockito.mock(NewsSourcesRestService.class);
 Mockito.when(mock.sources()).thenReturn(Single.just(newNewsSourceDataResponse()));
 return mock;
 }
 }
  • 27. Настройка сборки android {
 
 defaultConfig { 
 testInstrumentationRunner 'android.support.test.runner.AndroidJUnitRunner'
 
 }
 }
  • 28. @RunWith(AndroidJUnit4.class) @LargeTest
 public class SourceActivityTest {
 
 @Rule
 public IntentsTestRule<SourcesActivity> mActivityRule = new IntentsTestRule<>(SourcesActivity.class);
 
 @Test
 public void test() throws Exception {
 onView(withId(R.id.list))
 .check(matches(childCount(1)))
 .check(matches(hasDescendant(withId(R.id.name))));
 
 NewsSourcesResponseDto responseDto = NewsApiModule.newNewsSourceDataResponse();
 onView(withId(R.id.name))
 .check(matches(withText(responseDto.getSources().get(0).getName())));
 
 onView(withId(R.id.list))
 .perform(actionOnItemAtPosition(0, click()));
 
 ComponentName articlesActivity =
 new ComponentName(mActivityRule.getActivity(), ArticlesActivity.class);
 intended(hasComponent(articlesActivity));
 }
 }
  • 29. Espresso • Core • Contrib • Idling Resources • Intents • Web
  • 30. Материалы • JUnit4 • Mockito • Basic Guide • Robolectric • Android:Getting Started with Testing • Android Testing Support Library • Android Espresso • Android Testing Codelab