Retrofit Unit Test with Roboletric - unit-testing

Is there any possibility to test if Retrofit callback return success?
My code is quite simple:
#Config(constants = BuildConfig.class, sdk = 21,
manifest = "app/src/main/AndroidManifest.xml")
#RunWith(RobolectricGradleTestRunner.class)
public class RetrofitCallTest {
private MainActivity mainActivity;
#Mock
private RetrofitApi mockRetrofitApiImpl;
#Captor
private ArgumentCaptor<Callback<List<MyObject>>> callbackArgumentCaptor;
#Before
public void setUp() {
MockitoAnnotations.initMocks(this);
ActivityController<MainActivity> controller = Robolectric.buildActivity(MainActivity.class);
mainActivity = controller.get();
RestClient.setApi(mockRetrofitApiImpl);
controller.create();
}
#Test
public void shouldFillAdapter() throws Exception {
Mockito.verify(mockRetrofitApiImpl)
.getYourObject(callbackAgrumentCaptor.capture());
int objectsQuantity = 10;
List<MyObject> list = new ArrayList<YourObject>;
for(int i = 0; i < objectsQuantity; ++i) {
list.add(new MyObject());
}
callbackArgumentCaptor.getValue().success(list, null);
ListAdapter adapter = mainActivity.getAdapter();
assertThat(adapter .getItemCount(), equalTo(objectsQuantity));
}
It's clear - I test if my code works correctly WHEN api return success.
But is there any posibility to test IF api return success?

Related

Mocked repository is null when Mockito testing

I end up with my repository as null when testing a method in a service class. It is unclear what causes this for me.
In my service class I make use of a private RestTemplate that I setup as follows together with repository as #Mocks and service class #Injectmocks on :
...
#InjectMocks
#Spy
WorkService workService;
#Mock
private WorkJobRepository workJobRepository;
...
#Mock
RestTemplateBuilder mockedBuilder= Mockito.mock(RestTemplateBuilder.class);
#Mock
RestTemplate mockedRestTemplate = Mockito.mock(RestTemplate.class);
#BeforeEach
void setUp() {
ReflectionTestUtils.setField(listToPrintService, "restTemplate", mockedRestTemplate);
}
My test case in which repository is not passed (it is null):
#Test
void testGetRequestListToWork() {
ListToWork listToWork = getListToWork();
WorkJob WorkJob = getOneWorkJob();
ResponseEntity<String> responseEntity = getOneResponseEntityString(listToWork);
Mockito.doReturn(responseEntity).when(listToWorkService).getRequestListToWork(listToWork);
Mockito.when(listToWorkService.getRequestListToWork(listToWork)).thenAnswer(new Answer<ResponseEntity<String>>() {
#Override
public ResponseEntity<String> answer(InvocationOnMock invocation) {
return responseEntity;
}
});
String json = responseEntity.getBody().toString();
Mockito.when(listToWorkService.createNewWorkJob(json, listToWork)).thenReturn(WorkJob);
listToWorkService.getRequestListToWork(WorkJob);
assertEquals("xxx", repository.getById(listToWork.getId));
}
Here's the method I am trying to test:
public WorkJob getRequestListToWork(WorkJob WorkJob) {
ListToWork listToWork = new ListToWork(WorkJob.getTemplateId(), WorkJob.getStoreName(), WorkJob.getJobListId(), WorkJob.getId());
ResponseEntity<String> responseEntity = getRequestListToWork(listToWork);
Gson g = new Gson();
String json = responseEntity.getBody().toString();
WorkJob newWorkJob = createNewWorkJob(json,listToWork);
if(newWorkJob.getJobId() != -1 && newWorkJob.getJobState() != 12) {
pollForJobStatus(newWorkJob);
}
return newWorkJob;
}
Can anybody advise? What is causing the repository not to be passed?

How can i test that flexibleSearch works fine with .setCount()?

I have a java class that searches items, but in the method params this class receive a number of max items per query search (batchLines).
Class:
#Override
public List<OrderEntryItemModel> findOrderEntriesByStore(final BaseStoreModel store, final Date modifiedTime,
final int batchLines, final int start) {
final FlexibleSearchQuery query;
if (modifiedTime != null) {
query = new FlexibleSearchQuery(FIND_ORDER_ENTRY_ITEMS_BY_STORE_QUERY + MODIFIED_TIME_PARAM_QUERY);
query.addQueryParameter("modifiedtime", modifiedTime);
} else {
query = new FlexibleSearchQuery(FIND_ORDER_ENTRY_ITEMS_BY_STORE_QUERY);
}
query.setCount(batchLines);
query.setNeedTotal(true);
query.addQueryParameter("store", store);
query.setStart(start);
return getFlexibleSearchService().<OrderEntryItemModel>search(query).getResult();
}
So I have to test this class works fine with using .setCount(). I tried to do the test but always give me 3 and it must give me 1.
Test class:
#UnitTest
#RunWith(MockitoJUnitRunner.class)
public class DefaultLookerOrderEntryItemDaoTest {
private DefaultLookerOrderEntryItemDao lookerOrderEntryItemDao;
#Mock
private FlexibleSearchService flexibleSearchService;
#Mock
private SearchResult<OrderEntryItemModel> searchResult;
#Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
lookerOrderEntryItemDao = new DefaultLookerOrderEntryItemDao(flexibleSearchService);
final OrderEntryItemModel oei1 = new OrderEntryItemModel();
final OrderEntryItemModel oei2 = new OrderEntryItemModel();
final OrderEntryItemModel oei3 = new OrderEntryItemModel();
final List<OrderEntryItemModel> orderEntryItems = new ArrayList<>();
orderEntryItems.add(oei1);
orderEntryItems.add(oei2);
orderEntryItems.add(oei3);
given(flexibleSearchService.<OrderEntryItemModel>search(isA(FlexibleSearchQuery.class))).willReturn(searchResult);
given(searchResult.getResult()).willReturn(orderEntryItems);
}
#Test
public void findOrderEntries(){
given(searchResult.getCount()).willReturn(1);
final List<OrderEntryItemModel> orderEntries = lookerOrderEntryItemDao.findOrderEntriesByStore(new BaseStoreModel(), null, 1, 0);
assertEquals(1, orderEntries.size());
}
}

Spring WebFlux: Unit testing of Mono

I have the following service
#Service
public class TestService {
#Autowired
TestService1 testService1;
#Autowired
TestService2 testService2;
#Autowired
TestService3 testService3;
#Autowired
TestService4 testService4;
public Mono<DataResponse> getData() {
Mono<String> ts1 = testService1.getMono();
Mono<String> ts2 = testService2.getMono();
Mono<String> ts3 = testService3.getMono();
Mono<String> ts4 = testService4.getMono();
return Mono.zip(ts1, ts2, ts3, ts4)
.flatmap(resp -> {
// line XX
return(Mono.just(new DataResponse(ts1, ts2, ts3, ts4)));
});
}
}
I'm trying to perform unit testing using Mockito and JUnit.
#SpringBootTest()
public class TestService {
#InjectMocks
TestService testService;
#Mock(answer = Answers.RETURNS_DEEP_STUBS)
TestService1 testService1;
#Mock(answer = Answers.RETURNS_DEEP_STUBS)
TestService2 testService2;
#Mock(answer = Answers.RETURNS_DEEP_STUBS)
TestService3 testService3;
#Mock(answer = Answers.RETURNS_DEEP_STUBS)
TestService4 testService4;
#Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
}
#Test
public Mono<DataResponse> getData() {
when(testService1.getMono()).thenReturn(Mono.just(new String()));
when(testService2.getMono()).thenReturn(Mono.just(new String()));
when(testService3.getMono()).thenReturn(Mono.just(new String()));
when(testService4.getMono()).thenReturn(Mono.just(new String()));
Mono<DataResponse> res = testService.getData();
Predicate<DataResponse> p = response -> response != null;
StepVerifier.create(res.log(), 1).expectNextMatches(p).verifyComplete();
}
}
StepVerifier never executes expectNextMatches if I return Mono.zip(...) from the getData method and never executes code inside flatmap (line XX), the publisher is getting initialized but not able to subscribe to it. But if I return Mono.just() it is working fine.
Following are the logs
12:47:18.576 [main] INFO reactor.Mono.FlatMap.2 - | onSubscribe([Fuseable] MonoFlatMap.FlatMapMain)
12:47:18.587 [main] INFO reactor.Mono.FlatMap.2 - | request(1)
What would be the best approach to write unit test cases for this use case with 100% coverage?

Unit test verify method was called inside RxJava's doOnSuccess operator

I have the following code I'm trying to unit test :
if (networkUtils.isOnline()) {
return remoteDataSource.postComment(postId, commentText)
.doOnSuccess(postCommentResponse ->
localDataSource.postComment(postId, commentText))
.subscribeOn(schedulerProvider.io())
.observeOn(schedulerProvider.mainThread());
} else {
return Single.error(new IOException());
}
And this is how I'm trying to test it :
#Test
public void postComment_whenIsOnline_shouldCallLocalToPostComment() throws Exception {
// Given
when(networkUtils.isOnline())
.thenReturn(true);
String postId = "100";
String comment = "comment";
Response<PostCommentResponse> response = postCommentResponse();
when(remoteDataSource.postComment(anyString(), anyString()))
.thenReturn(Single.just(response));
// When
repository.postComment(postId, comment);
// Then
verify(localDataSource).postComment(postId, comment);
}
where I fake Response from Retrofit like :
private Response<PostCommentResponse> postCommentResponse() {
PostCommentResponse response = new PostCommentResponse();
response.setError("0");
response.setComment(postCommentResponseNestedItem);
return Response.success(response);
}
but it results to : Actually, there were zero interactions with this mock.
Any ideas ?
EDIT :
#RunWith(MockitoJUnitRunner.class)
public class CommentsRepositoryTest {
#Mock
private CommentsLocalDataSource localDataSource;
#Mock
private CommentsRemoteDataSource remoteDataSource;
#Mock
private NetworkUtils networkUtils;
#Mock
private PostCommentResponseNestedItem postCommentResponseNestedItem;
private CommentsRepository repository;
#Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
BaseSchedulerProvider schedulerProvider = new ImmediateSchedulerProvider();
repository = new CommentsRepository(localDataSource, remoteDataSource, networkUtils, schedulerProvider);
}
// tests
}
When you want to test an Observable you have to subscribe to it so it will start emitting items.
As soon as I used :
TestObserver<Response<PostCommentResponse>> testObserver = new TestObserver<>();
and subscribed to :
repository.postComment(postId, comment)
.subscribe(testObserver);
the test worked as expected.

Mockito ClassCastException with casting field

I'm trying to write unit test for the following code:
public DesiredCapabilities findCapability(Platforms platform, Types type, String browser, double platformVersion) throws Exception{
Criteria criteria = getSession().createCriteria(BrowserCapabilities.class)
.add(Restrictions.eq("status", ICommonConstants.DB_STATUS_ACTIVE))
.add(Restrictions.eq("platformName", platform.getValue()))
.add(Restrictions.eq("browserName", browser))
.add(Restrictions.eq("platformVersion", platformVersion))
.addOrder(Order.desc("browserVersion"))
.setMaxResults(1);
Object res = criteria.uniqueResult();
if(res!=null)
return this.prepareBrowserCapability((BrowserCapabilities)res);
return null;
}
The mock code is:
private BrowserCapabilityDAO mockBrowserCapability;
private Session mockSession;
private Criteria mockCriteria;
private Criterion mockCriterion;
#Before
public void init() {
mockBrowserCapability = Mockito.spy(new BrowserCapabilityDAO());
mockSession = Mockito.mock(Session.class, Mockito.RETURNS_DEEP_STUBS);
mockCriteria = Mockito.mock(Criteria.class, Mockito.RETURNS_DEEP_STUBS);
mockCriterion = Mockito.mock(Criterion.class, Mockito.RETURNS_DEEP_STUBS);
}
#Test
public void testFindCapability() throws Exception {
DesiredCapabilities desiredCapability = new DesiredCapabilities();
BrowserCapabilities mockBrowserCapabilities = getMockBrowserCapabilities();
//Stub
Mockito.doReturn(mockSession).when(mockBrowserCapability).getSession();
Mockito.when(mockSession.createCriteria(Mockito.eq(BrowserCapabilities.class))).thenReturn(mockCriteria);
Mockito.doReturn(mockCriteria).when(mockCriteria).add(mockCriterion);
Mockito.when(mockCriteria.addOrder(Mockito.any(Order.class))).thenReturn(mockCriteria);
Mockito.when(mockCriteria.setMaxResults(Mockito.anyInt())).thenReturn(mockCriteria);
Mockito.when(mockCriteria.uniqueResult()).thenReturn((Object)mockBrowserCapabilities);
//Mockito.doReturn(desiredCapability).when(mockBrowserCapability).prepareBrowserCapability(mockBrowserCapabilities);
mockBrowserCapability.findCapability(Platforms.WINDOWS, Types.COMPUTER, "FF", 10.0);
}
private BrowserCapabilities getMockBrowserCapabilities() {
BrowserCapabilities mockBrowserCapabilities = new BrowserCapabilities();
mockBrowserCapabilities.setBrowserName("browserName");
mockBrowserCapabilities.setBrowserVersion("browserVersion");
return mockBrowserCapabilities;
}
But I'm getting the ClassCastException at line:
return this.prepareBrowserCapability((BrowserCapabilities)res);
cannot be cast to com.common.xxx.persistence.beans.BrowserCapabilities.