I have started creating an app as a private project and I want to cover it in unit tests. For now I have only made some of them for the model classes and now I tried to do it for a custom array adapter without success. I am a beginner in Android testing overall and currently I have found that i need to use android tests instead of unit tests. At the moment I fail to get the context of my fragment.
@RunWith(RobolectricTestRunner.class)
public class MyFragmentTest {
private MainActivity activity;
private TripInputFragment fragment;
@Before
public void setup() {
activity = Robolectric.buildActivity(MainActivity.class).create().visible().get();
fragment = new TripInputFragment();
activity.getSupportFragmentManager().beginTransaction().add(fragment, null).commit();
}
@Test
public void testFragment() {
}
@After
public void tearDown() {
activity.getSupportFragmentManager().beginTransaction().remove(fragment).commit();
}
}
I've tried it this way, but this code fails with error message: No virtual method getAnnotatedParameterTypes().
I have also tried other options, but the getview(...) in my array adapter returns id -1, when trying to inflate the layout. They layout files are valid, I am successfully using them in code, so I think that this is connected to the context.
At first I uploaded only the initialization code, because it failed at that step, but after the comment was made I am updating the code to show how I try to test the adapter now (I got rid of roboelectric for now since I can't get it to work):
@Test
public void dayOfWeekAdapterTest() {
Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
int resource = R.layout.list_item_layout;
List<Trip> trips = new ArrayList<>();
trips.add(new Trip("Saturday", "Berlin", "Lisbon"));
DayOfWeekAdapter adapter = new DayOfWeekAdapter(appContext, resource, trips);
View view = adapter.getView(0, null, null);
TextView dayOfWeektext = view.findViewById(R.id.trip_day_of_week);
Log.i("view", String.valueOf(view.getId()));
Log.i("view", trips.get(0).getDayOfWeek());
Log.i("view", (String) dayOfWeektext.getText());
assertEquals(trips.get(0).getDayOfWeek(), dayOfWeektext.getText());
}
The assert works here and I get correct result. What I can't get is a view itself from a getView() method. The id returns -1. How could I assert expected view and then get the actual view and test if they are the same view?
The view id thing was kind of unrelated, because I haven't set the id of the layout, so that was the case here. My last question for now would be: is it possible to somehow assertEquals the view object to an expected view object or should I just create a new view and give it an id and check if id is the same in the actual view?