1

I fill the Cursor and FragmentManager value inside the PageAdapter class but during Test process it brings Cursor and FragmentManager as null for always.

How i can configure Test to get Cursor and FragmentManager with a valid value?

public class PagerAdapter extends FragmentStatePagerAdapter {
  private Cursor mCursor;

  public PagerAdapter(FragmentManager fm, Cursor aCursor) {
    super(fm);
    mCursor = aCursor;
  }

Test code block is below:

@RunWith(MockitoJUnitRunner.class)
public class PagerAdapterTest extends Assert{
  @Mock
  private PagerAdapter mPagerAdapter;

  private FragmentManager fm;
  private Cursor mCursor;

  @Before
  public void setUp() throws Exception {
    mPagerAdapter = new PagerAdapter(fm, mCursor);
  }
GhostCat
  • 137,827
  • 25
  • 176
  • 248
hpolat
  • 23
  • 6
  • Possible duplicate of [Is Java "pass-by-reference" or "pass-by-value"?](https://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value) – GhostCat Aug 02 '17 at 10:39
  • This code can **not** work! The references `fm` and `mCursor` will **not** change when you assign values to variables which are parameters of a method. This will break always, not only in your unit test. This simply fundamentally wrong on a basic java level. – GhostCat Aug 02 '17 at 10:40
  • I have to build and fill object for the `unit test`. I'm looking for a way to do this and I'm stucked :( Do you have a suggestion for me to fill in these objects? – hpolat Aug 02 '17 at 11:19
  • Yes, I do not know enough about using the cursor at this stage. If I dominate the use of Cursor, I will write a reply under this question. – hpolat Aug 09 '17 at 07:01

1 Answers1

3

Your problem is "simple" - in your test code:

private FragmentManager fm;
private Cursor mCursor;

are both null. SO this:

mPagerAdapter = new PagerAdapter(fm, mCursor);

Maybe you assumed that @Mock mocks all fields - nope, sorry: it only mocks the first field declared afterwards!

So your code is just doing new PageAdapter(null, null). The point is: you need to mock various core infrastructure elements that are provided by the Android system in the "real world".

And beyond that, you seem to not understand how mocking and unit tests come together. You want to test your PageAdapter class - and in that case it makes no sense to mock the PageAdapter class. You create mocks for those objects that you need to feed into your class under test to test that class. In that sense, you should first study the basics of unit testing and mocking (ideally without the complexity added by Android). Start reading here for example.

And then, when you "got that part", read and follow the extensive documentation that explains to you how to establish a "working" unit test environment for Android. See here for example.

GhostCat
  • 137,827
  • 25
  • 176
  • 248