Last active
February 4, 2018 18:02
-
-
Save mohsenoid/888c6111ddfdd392cd84660f04f58afb to your computer and use it in GitHub Desktop.
Sample jUnit Test https://hackernoon.com/yet-another-mvp-article-part-5-writing-test-using-a-mixture-of-dagger-and-espresso-15c638182706
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.mirhoseini.marvel.character.search; | |
/*...*/ | |
import org.junit.Before; | |
import org.junit.Test; | |
import java.util.Collections; | |
import rx.Observable; | |
import rx.observers.TestSubscriber; | |
import rx.schedulers.Schedulers; | |
import static org.mockito.Matchers.any; | |
import static org.mockito.Mockito.mock; | |
import static org.mockito.Mockito.when; | |
public class SearchInteractorTest { | |
SearchInteractor interactor; | |
MarvelApi api; | |
SchedulerProvider scheduler; | |
CharactersResponse expectedResult; | |
@Before | |
public void setup() { | |
api = mock(MarvelApi.class); | |
scheduler = mock(SchedulerProvider.class); | |
// Set up the stub we want to return in the mock | |
Results character = new Results(); | |
character.setName("Test Character"); | |
Results[] characters = new Results[1]; | |
characters[0] = character; | |
Data charactersData = new Data(); | |
charactersData.setResults(characters); | |
// put the test character in a test api result | |
expectedResult = new CharactersResponse(); | |
expectedResult.setData(charactersData); | |
// mock scheduler to run immediately | |
when(scheduler.mainThread()) | |
.thenReturn(Schedulers.immediate()); | |
when(scheduler.backgroundThread()) | |
.thenReturn(Schedulers.immediate()); | |
// mock api result with expected result | |
when(api.getCharacters(any(String.class), any(String.class), any(String.class), any(Long.class))) | |
.thenReturn(Observable.just(expectedResult)); | |
// create a real new interactor using mocked api and scheduler | |
interactor = new SearchInteractorImpl(api, scheduler); | |
} | |
@Test | |
public void testLoadCharacters() throws Exception { | |
TestSubscriber<CharactersResponse> testSubscriber = new TestSubscriber<>(); | |
// call interactor with some random params | |
interactor.loadCharacter("query", "privateKey", "publicKey", 1) | |
.subscribe(testSubscriber); | |
// it must return the expectedResult with no error | |
testSubscriber.assertNoErrors(); | |
testSubscriber.assertReceivedOnNext(Collections.singletonList(expectedResult)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment