Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Mockito how to mock a resource

I am using robolectric as my test runner with Mockito. I would like to know in Android how do i mock a resource. I have a array resource but in my test i'd like to mock the value.

i have an array that looks like this:

 <array name="screen_sections">
        <item>screen1</item>
        <item>screen2</item>
        <item>screen3</item>
        <item>screen4</item>
    </array>

and in test code i'd like to mock these values.

like image 649
j2emanue Avatar asked Nov 10 '15 21:11

j2emanue


People also ask

What is stubbing in Mockito?

A stub is a fake class that comes with preprogrammed return values. It's injected into the class under test to give you absolute control over what's being tested as input. A typical stub is a database connection that allows you to mimic any scenario without having a real database.

How do you mock an object in JUnit?

We can use Mockito class mock() method to create a mock object of a given class or interface. This is the simplest way to mock an object. We are using JUnit 5 to write test cases in conjunction with Mockito to mock objects.


1 Answers

I found a way to do this using Mockito.when. So I would create a normal array and save it with my values, something like this works good:

CharSequence myNewArray = {"value1","value2","value3"}
Mockito.when(resources.getTextArray(someID)).thenReturn(myNewArray);
like image 192
j2emanue Avatar answered Sep 23 '22 20:09

j2emanue