This is the first post. Do you use "Mockito"?
I used Android Studio for business to create an application, and when I did a Unit Test, I had a fight with Mockito, so I will post it to make friends with Mockito and as my memorandum.
The application I was creating was provided with an interface by aidl and was an application that binds to the service.
Initially, I used Robolectric's ShadowApplication.setComponentNameAndServiceForBindService ()
to pass a Mocked IBinder, but when I retrieve the interface with ʻIBinder.Stub.asInterface ()`, it becomes a different object. I wasn't able to make it into a Mock.
(Maybe my Mock was simply wrong.)
It seems that static methods can also be Mocked from Mockito 3.4.0, but I could not find any useful information on the Web, so I will show it below.
ʻHow to mock static methods such as IBinder.Stub.asInterface ()`. You can make it a Mock by the following usage.
final IMyService mockMyService = mock(IMyService.class); // ⭐︎1
try(final MockedStatic<IMyService.Stub> mockedStatic = mockStatic(IMyService.Stub.class)) {
// ↓ The return value of IMyService.Stub.asInterface () will be the mocked IMyService (⭐︎1).
mockedStatic.when(() -> IMyService.Stub.asInterface(any())).thenReturn(mockMyService);
// Please test with bindService () in Activity etc. below.
final ActivityController
By performing the above operation, you can make a static method into a Mock.
In the above, it is described as try-with-resources
, but if it is not described as try-with-resources
, please perform close ().
final MockedStatic<IMyService.Stub> mockedStatic = mockStatic(IMyService.Stub.class);
...
mockedStatic.close();
You can also Mock a class that is new
in a method with Mockito.
final MockedConstruction<SubClass> mockedConstruction = mockConstruction(SubClass.class);
// You can get the new class below
// Since the acquired class is Mocked, you can change the return value etc. using when ().
List
Since this is my first post, I'm not sure if I can explain it well.
I hope it helps someone even a little.
The Mock conversion method introduced this time is only a part.
Both MockedStatic
andMockedConstruction
have several types of constructors, so [Mockito's official documentation](https://javadoc.io/static/org.mockito/mockito-core/3.5.9/org/mockito/ Please refer to Mockito.html) and try various things with IDE such as Android Studio.
Recommended Posts