Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Unittesting with Databinding

I'm now working on a very good project, where we introduced Android databinding. Everything works fine in the code, binding perfectly, but when it comes to unit testing I'm not able to test my code. I'm struggling to MOCK the databinding...

When adding this line to setUp() method:

PowerMockito.when(DataBindingUtil.class, "inflate", inflater,anyInt(),any(ViewGroup.class),anyBoolean()).thenReturn(viewDataBinding.getRoot());

I'll have the following error message:

...thenReturn() may be missing.

As you can see, I have thenReturn at the end, but Mockito doesn't see it.

I tried to move the code into a concrete test method:

  @Test
public void createViewHolder() {
  .... CODE....
 when(DataBindingUtil.inflate(inflater,anyInt(),any(ViewGroup.class),anyBoolean())).thenReturn(viewDataBinding);
... CODE ...}

In this case I'll have the following message:

org.mockito.exceptions.misusing.WrongTypeOfReturnValue: ViewDataBinding$$EnhancerByMockitoWithCGLIB$$f5f40ad1 cannot be returned by inflate() inflate() should return View

I don't understand, why I getting this message, since DataBindingUtil.inflate is returning a ViewDataBinding in the code, where it's works perfectly. Have any of you ever tried to mock and unit test data binding on Android?

like image 663
narancs Avatar asked Oct 31 '22 00:10

narancs


1 Answers

Ok the issue was the following: Need to add:

@PrepareForTest({DataBindingUtil.class}) to the beginning of the class

PowerMockito.mockStatic(DataBindingUtil.class);
PowerMockito.mockStatic(ViewDataBinding.class);

I had to add these lines to the setUp();

then:

when(DataBindingUtil.inflate(eq(inflater), anyInt(), any(ViewGroup.class), anyBoolean())).thenReturn(viewDataBinding);
when(viewDataBinding.getRoot()).thenReturn(itemView);

into the test itself.

like image 145
narancs Avatar answered Nov 11 '22 13:11

narancs