Mockito To Verify ArrayList Size - android

My Adapter has getItemCount method in which ArrayList returns size of items. How to i verify it with Mockito as i don't have any view in that method?
static class SongAdapterPresenter implements SortedSongSelectionContract.SongAdapterContract.Presenter {
.....
....
#Override
public int getItemCount() {
return songs != null ? songs.size() : 0;
}
}
My Mockito Class code
#RunWith(PowerMockRunner.class)
#PrepareForTest(Log.class)
public class SongAdapterPresenterTest {
private SortedSongSelectionPresenter.SongAdapterPresenter songAdapterPresenter;
#Mock
private SortedSongSelectionContract.SongAdapterContract.Adapter adapter;
#Mock
private SortedSongSelectionContract.Presenter presenter;
#Mock
private Song song;
private List<Song> songList;
#Before
public void setUp(){
songList=new ArrayList<>(1);
songList.add(song);
songAdapterPresenter=new SortedSongSelectionPresenter.SongAdapterPresenter(adapter,presenter);
}
#Test
public void testGetItemCount(){
songAdapterPresenter.getItemCount();
verify(songList.size()).equals(1);
}
#Test
public void testonBindView(){
}
}
When i run the testGetItemCount method i get org.mockito.exceptions.misusing.NotAMockException:
Any help would be greatly appreciated

The verify method of Mockito is used to interact with a mock, and make sure it was used as intended. For example, you could write verify(song).something() to make sure that the something method was called on the song mock.
In your case it looks like you are just looking for a way to verify (assert) the returned value. As this has nothing to do with your song mock, you should use a framework like Hamcrest with its assertThat method:
#Test
public void testGetItemCount() {
int count = songAdapterPresenter.getItemCount();
assertThat(count, is(1));
}
You can write assertions in any way you feel comfortable. As you're not interacting with a mock (song in your case), this is not the place to use Mockito.

Related

Mockito 3.4.0 Static Mocking Exception

I am getting the following exception when trying to mock the static method.
For SettingsUtility, static mocking is already registered in the
current thread To create a new mock, the existing static mock
registration must be deregistered
#Before
fun setUp() {
mockStatic(SettingsUtility::class.java) {
`when` { SettingsUtility.method(app) }.thenReturn { "" }}
}
The returned object's MockedStatic.close() method must be called upon completing the test or the mock will remain active on the current thread.
I am not sure if it is the same as how its done in Java. Hope this Java code snippet helps
private static MockedStatic<SettingsUtility> mockedSettings;
#BeforeAll
public static void init() {
mockedSettings = mockStatic(SettingsUtility.class);
}
#AfterAll
public static void close() {
mockedSettings.close();
}
Try doing this way, you will not get this error. It worked for me.
try(MockedStatic mocked = mockStatic(SettingsUtility.class)) {
mocked.when(SettingsUtility::method).thenReturn("whatever you want");
}
Building on #Sudha 's answer.
in Java you can use #BeforeClass and #AfterClass
private static MockedStatic<SettingsUtility> mockedSettings;
#BeforeClass
public static void init() {
mockedSettings = mockStatic(mockedSettings.class);
}
#AfterClass
public static void close() {
mockedSettings.close();
}
Mockito Inline works differently than the Mockito hence the failure. So what needs to be done is initialise and close the mocks explicitly.
You need to initialise the mockedStatic for your class
private MockedStatic<YourClassWithStaticMethod> mockedStatic;
Then add below code in BeforeEach and AfterEach
#BeforeEach
public void init() {
mockedStatic = mockStatic(YourClassWithStaticMethod.class);
}
#AfterEach
public void cleanup() {
mockedStatic.close();
}
And now you can set the mocked expectations.
mockedStatic.when(YourClassWithStaticMethod::staticMethodToMock).thenReturn(yourReturnedMockedObject);
I tried below and worked for me.
MockedStatic mockedStatic = mockStatic(SettingsUtility.class)
mocked.when(SettingsUtility::method).thenReturn("any thing");
...........
//do all stuf
and at last close the mock
mockedStatic.close();

Why is Mockito boolean stub being ignored

I have a method that checks a condition and does some work.
public void doSomeWork(){
if(!UtilityClass.someCondition()){
context.getmeSomething();
}
}
My test looks like this.
#Test
public void test(){
myClass.doSomeWork();
PowerMockito.verifyStatic(UtilityClass.class)
when(UtilityClass.someCondition()).thenReturn(false);
verify(mContext, times(1)).getmeSomething();
}
The problem is the stub is simply ignored. The test passes regardless of the stub result. By the same token, never verification on fails and I get Never wanted at the test but wanted at my class under test from Mockito. My question is why the boolean stub being ignored?
Update
I am not sure if it is significant with my original question, but the Utility class is included in the prepare for test and has mockStatic call in setUp.
Ordering of your statements!
Register your mocks and behaviour of it.
Call the method
Verify
EDIT:
you should also make sure, that UtilityClass is a mock. You can't stub actual classes, just mocks of them.
#Rule
public MockitoRule rule = MockitoJUnit.rule();
#Mock
private UtilityClass utilityClassMock;
private MyClass myClass;
#Before
public void beforeEachTest() {
myClass = new MyClass(utilityClassMock);
}
#Test
public void test(){
when(utilityClassMock.someCondition).thenReturn(false);
myClass.doSomeWork();
verify(mContext, times(1)).getmeSomething();
}
Just like GabrielJoerg said the stubbing should happen first before the method call. But the real issue here is that when stubbing, you should avoid calling verifyStatic. Here is what worked for me.
#Test
public void test(){
when(UtilityClass.someCondition()).thenReturn(false);
myClass.doSomeWork();
verify(mContext, times(1)).getmeSomething();
}

how to test private Observable inside public method?

I am new with tests.
I have something like next code and wish to cover it with unitTests using the Mockito:
public void doSomeJob(){
//some code before
getMvpView().execute(getObservable());
//some code after
}
private Observable<Boolean> getObservable(){
return Observable.create(new ObservableOnSubscribe<Boolean>() {
#Override
public void subscribe(#NonNull ObservableEmitter<Boolean> e) throws Exception {
Thread.sleep(5000);
e.onNext(true);
e.onComplete();
}
});
}
so questions:
how correct write test for getMvpView().execute(getObservable()); using Mokito?
how can i verify result of getObservable()?
If your private method is not a part of the interface, i.e. cannot be reached from outside the class, it's not something you should test (presumably it's not, since it's private). Mockito in turn doesn't provide mocking of private methods. Thereby you either need to change your interface (make this data available outside) or leave it without testing.
What you should test is the effect of calling the public methods of your class under test. If you do so you will be able to freely refactor the implementation details later, and your tests will still verify that your class works as expected.
I suppose that your code is part of a presenter implementation and the getMvpView() method returns a view interface:
public class MvpPresenterImpl {
private MvpView view;
public void doSomeJob(){
//some code before
getMvpView().execute(getObservable());
//some code after
}
public void attachView(MvpView view) {
this.view = view;
}
private MvpView getMvpView() {
return view;
}
private Observable<Boolean> getObservable(){
return Observable.create(new ObservableOnSubscribe<Boolean>() {
#Override
public void subscribe(#NonNull ObservableEmitter<Boolean> e) throws Exception {
Thread.sleep(5000);
e.onNext(true);
e.onComplete();
}
});
}
}
You can test the effect of doSomeJob() like so:
public class MvpPresenterImplTest {
private MvpPresenterImpl presenter;
private MvpView mockView;
#Before
public void setUp() throws Exception {
// Create a mock view instance so that we can verify method calls on it
mockView = mock(MvpView.class);
// Create our object under test, and set it up with the mock view
presenter = new MvpPresenterImpl();
presenter.attachView(mockView);
}
#Test
public void doSomeJob_callsExecuteOnViewWithCorrectObserver() throws Exception {
// What we want to test is the effect of invoking a public method.
presenter.doSomeJob();
// Verify that the execute method has been called by your class
// under test, and save the parameter for later.
ArgumentCaptor<Observable<Boolean>> paramCaptor =
ArgumentCaptor.<Observable<Boolean>>forClass((Class)Observable.class);
verify(mockView).execute(paramCaptor.capture());
// Get the actual observable that the execute method was called with.
Observable<Boolean> param = paramCaptor.getValue();
// Get a test observer so that we can check what our Observable emits
// (TestObserver is a built-in feature of RxJava, not Mockito.)
TestObserver<Boolean> test = param.test();
// Assert that the Observable behaves as expected
test.assertComplete();
test.assertResult(true);
}
}

How to mock Callback answer for static methods with PowerMock?

I need to mock some static methods, that's fine so far and can be done like this:
#RunWith(PowerMockRunner.class)
#PrepareForTest({DataService.class})
public class PlayersAllViewModelTest {
// mock objects
private PlayersAllContextHandler mContextHandler;
private PlayersAllAdapter mAdapter;
#Before
public void setUp() throws Exception {
mockStatic(DataService.class);
//define mocks
mContextHandler = mock(PlayersAllContextHandler.class);
mAdapter = mock(PlayersAllAdapter.class);
}
#Test
public void check_init_requests_are_done() throws Exception {
// create instance of viewmodel
new PlayersAllViewModel(mContextHandler, mAdapter);
// check dataservice is requested for method 'getAllPlayers()'
PowerMockito.verifyStatic();
DataService.getAllPlayers(any(DataServiceCallback.class));
}
I need to test the behavior for a given response (success() / failure()) answered in a callback. The normal way to do so is like this:
// define mock answer
doAnswer(new Answer<MyCallback<String>>() {
#Override
public MyCallback answer(InvocationOnMock invocation) throws Throwable {
MyCallback<Player> callback = (MyCallback<Player>) invocation.getArguments()[0];
callback.onFailure(new UnsupportedOperationException());
return null;
}
}).when(>>mocked class instance<<).myTestMethod(any(MyCallback.class));
Because is want to call a static method, i can't do it like that so. There's no mocked instance of a class that could fill the gap :(
Does anybody know what's the correct way to do it?

Mocking findViewById response with Robolectric and Mockito

I have a custom ListView say CustomListView:
In a fragment there is:
<com.custom.CustomListView
android:id="#+id/custom_listview"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
and in that fragment's source, I have
private CustomListView mCustomListView;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mContext = getActivity();
mCustomListView = mContext.findViewById(R.id.custom_listview);
}
Then there is some method later:
public void doSomethingOnReceivingData(Data data) {
mCustomListView.someCustomMethod(data);
}
I want to write test for doSomethingOnReceivingData(Data) method.
I can not figure out how to mock the listview so that I can continue with the test (ArgumentCaptors and stuff)?
I would give to list field package local access and mock it in test directly. For our app it is already package accessible since we use Butterknife
#RunWith(MockitoJUnitRunner.class)
public class MainActivityFragmentTest {
#Mock
private CustomListView mCustomListView;
#InjectMocks
private MainActivityFragment fragment;
#Test
public void doSomethingOnReceivingData_callsCustomListView() {
final String data = "data";
fragment.doSomethingOnReceivingData(data);
verify(mCustomListView).someCustomMethod(eq(data));
}
}

Categories

Resources