0

I'm working with android in Java.

Our goal is to test a fragment of our app in isolation.

Our problem is that we need to setup a view-model double to in order to create meaningful and test worthy fragment state.

In particular, the model-view that models our fragment depends on another view model.

In our research, we learned that view-models are stored in some specific view-model-store object, is there a way to manipulate this storage location from espresso in a conventional not to hacky way? via maybe some interaction with a FragmentScenrario object?

The figure ilustrates our situation.

enter image description here

I'm appending my fragment code to clarify the way I'm injecting the view-model:

public class CornerDetectionFragment extends Fragment {
    private CornerDetectionViewModel cornerDetectionViewModel;
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        cornerDetectionViewModel =
                ViewModelProviders.of(
                        this,
                        new CornerDetectionViewModelFactory(getActivity())
                ).get(CornerDetectionViewModel.class);
        View root =inflater.inflate(R.layout.fragment_corner_detection, container, false);
        ((TextView)root.findViewById(R.id.textView_relative_cirrent_location)).setText(
                "1/"+cornerDetectionViewModel.getNumberOfCornerDetectedCaptures().getValue()
        );
        return inflater.inflate(R.layout.fragment_corner_detection, container, false);
    }
/*...*/
}

And also the code of the view-model factory:

public class CornerDetectionViewModelFactory implements ViewModelProvider.Factory {
    FragmentActivity activity;

    public CornerDetectionViewModelFactory(FragmentActivity activity) {
        this.activity = activity;
    }

    @NonNull
    @Override
    public <T extends ViewModel> T create(@NonNull Class<T> modelClass) {
        return (T) ViewModelProviders.of(
                activity,
                new InitialFactory())
                .get(CornerDetectionViewModel.class
                );
    }

    private class InitialFactory implements ViewModelProvider.Factory{
        @NonNull
        @Override
        public <T extends ViewModel> T create(@NonNull Class<T> modelClass) {
            return (T)new CornerDetectionViewModel(
                    new ImageProcessingFactory().create(),
                    new ResolveAnswersViewModelFactory(activity)
                            .create(ResolveAnswersViewModel.class)
            );
        }
    }
}

Thanks.

Rotem Barak
  • 154
  • 1
  • 9

0 Answers0