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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With