Получение контекста из ViewModel в тестировании - PullRequest
0 голосов
/ 17 октября 2019

Итак, у меня есть ViewModel с методом для получения данных с использованием контекста. Но при тестировании данные являются нулевыми, потому что при тестировании, возможно, нет контекста.

Код выглядит следующим образом:

Это тестирование кода ViewModel

public class FilmViewTest {
private FilmView filmView;

@Before
public void setUp() {
    Application context = Mockito.mock(Application.class);
    filmView = new FilmView(context);
    FilmData filmData = new FilmData(context);
}

// ubah poster menjadi link

@Test
public void getFilms() {
    List<ResultsItem> films = filmView.getFilms();
    assertNotNull(films);
    assertEquals(10, films.size());
}

}

и здесьэто сама ViewModel

public class FilmView extends AndroidViewModel {


public FilmView(@NonNull Application application) {
    super(application);
}

private Context context = getApplication().getApplicationContext();

private FilmData filmData = new FilmData(context);

public List<ResultsItem> getFilms() {
    return FilmData.generateFilms();
}
}

класс данных

public class FilmData {

private static Context context;

public FilmData(Context context) {
    FilmData.context = context;
}

public static ArrayList<ResultsItem> generateFilms() {

    ArrayList<ResultsItem> courses = new ArrayList<>();


courses.add(new ResultsItem(
            "A Star is Born",
            "Seasoned musician Jackson Maine discovers — " +
                    "and falls in love with — struggling artist Ally." +
                    " She has just about given up on her dream to make it big as a singer — until Jack coaxes her into the spotlight. But even as Ally's career takes off, the personal " +
                    "side of their relationship is breaking down, as Jack fights an ongoing battle with his own internal demons.",
            context.getResources().getDrawable(R.drawable.poster_a_start_is_born),

            346, " February 19, 2019", 75, 50));
    courses.add(new ResultsItem("Aquaman",
            "Once home to the most advanced civilization on Earth, Atlantis is now an underwater kingdom ruled by the power-hungry King Orm. With a vast army at his disposal, Orm plans to conquer the remaining oceanic people and then the surface world. " +
                    "Standing in his way is Arthur Curry, Orm's half-human, " +
                    "half-Atlantean brother and true heir to the throne.",
            context.getResources().getDrawable(R.drawable.poster_aquaman),
            238, "December 21, 2018", 68, 60));

    courses.add(new ResultsItem("Bohemian Rhapsody ",
            "Singer Freddie Mercury, guitarist Brian May, drummer Roger Taylor and bass guitarist John Deacon take the music world by storm when they form the rock 'n' roll band Queen in 1970. Hit songs become instant classics. When Mercury's increasingly wild lifestyle starts to spiral out of control, " +
                    "Queen soon faces its greatest challenge yet – " +
                    "finding a way to keep the band together amid the success and excess.",
            context.getResources().getDrawable(R.drawable.poster_bohemian),

            892, "November 2, 2018", 80, 299));

    courses.add(new ResultsItem("Alita: Battle Angel ",
            "When Alita awakens with no memory of who she is in a future world she does not recognize, she is taken in by Ido, a compassionate doctor who realizes that" +
                    " somewhere in this abandoned cyborg " +
                    "shell is the heart and soul of a young woman with an extraordinary past.\n",
            context.getResources().getDrawable(R.drawable.poster_alita),

            289, "January 31, 2019", 69, 15 ));

    courses.add(new ResultsItem(
                    "Cold Pursuit",
                    "The quiet family life of Nels Coxman, a snowplow driver, is upended after his son's murder. Nels begins a vengeful hunt for Viking, the drug lord he holds responsible for the killing, eliminating Viking's associates one by one. As Nels draws closer to Viking, his actions bring even more unexpected and violent consequences, as he proves that revenge is all in the execution.",
                    context.getResources().getDrawable(R.drawable.poster_cold_persuit),

            54, "February 7, 2019", 54, 219));

            courses.add(new ResultsItem(
                    "Creed",
                    "The former World Heavyweight Champion Rocky Balboa serves as a trainer and mentor to Adonis Johnson, the son of his late friend and former rival Apollo Creed.",
                    context.getResources().getDrawable(R.drawable.poster_creed),

                    129, "November 25, 2015", 73, 281));

    courses.add(new ResultsItem("Fantastic Beasts: The Crimes of Grindelwald",
            "Gellert Grindelwald has escaped imprisonment and has begun gathering followers to his cause—elevating wizards above all non-magical beings. The only one capable of putting a stop to him is the wizard he once called his closest friend, Albus Dumbledore. However, Dumbledore will need to seek help from the wizard who had thwarted Grindelwald once before, his former student Newt Scamander, who agrees to help, unaware of the dangers that lie ahead. Lines are drawn as love and loyalty are tested, even among the truest friends and family, in an increasingly divided wizarding world.",
            context.getResources().getDrawable(R.drawable.poster_crimes),

            123, "November 14, 2018", 69, 210));

    courses.add(new ResultsItem("Glass ",
            "In a series of escalating encounters, former security guard David Dunn uses his supernatural abilities to track Kevin Wendell Crumb, a disturbed man who has twenty-four personalities. Meanwhile, the shadowy presence of Elijah Price emerges as an orchestrator who holds secrets critical to both men.",
            context.getResources().getDrawable(R.drawable.poster_glass).getCurrent(),

            213, "January 16, 2019", 66, 190));

    courses.add(new ResultsItem("How to Train Your Dragon ",
            "As the son of a Viking leader on the cusp of manhood, shy Hiccup Horrendous Haddock III faces a rite of passage: he must kill a dragon to prove his warrior mettle. But after downing a feared dragon, he realizes that he no longer wants to destroy it, and instead befriends the beast – which he names Toothless – much to the chagrin of his warrior father",
            context.getResources().getDrawable(R.drawable.poster_how_to_train),

            319, "March 10, 2010", 77, 219));

    courses.add(new ResultsItem(
            "Avengers: Infinity War",
            "As the Avengers and their allies have continued to protect the world from threats too large for any one hero to handle, a new danger has emerged from the cosmic shadows: Thanos. A despot of intergalactic infamy, his goal is to collect all six Infinity Stones, artifacts of unimaginable power, and use them to inflict his twisted will on all of reality. Everything the Avengers have fought for has led up to this moment - the fate of Earth and existence itself has never been more uncertain.",
            context.getResources().getDrawable(R.drawable.poster_infinity_war),

            193, "April 25, 2018", 83, 21933));

    return courses;
}

}

это дает нулевую ошибку в методах

java.lang.NullPointerException
at com.example.movietv.film.utils.FilmData.generateFilms(FilmData.java:28)
at com.example.movietv.film.adapter.FilmView.getFilms(FilmView.java:26)
at com.example.movietv.film.adapter.FilmViewTest.getFilms(FilmViewTest.java:32)

Любая помощьбудет оценено! Спасибо!

1 Ответ

1 голос
/ 17 октября 2019

В идеале, вы не должны передавать весь рисуемый объект в модель context.getResources().getDrawable(R.drawable.poster_infinity_war). Вместо этого просто передайте int ресурса как

new ResultsItem("How to Train Your Dragon ",
            "As ... father", R.drawable.poster_how_to_train,
         319, "March 10, 2010", 77, 219)

Примечание. Вам необходимо соответствующим образом изменить модель ResultsItem

, а затем, когда вы фактически визуализируетеэто в адаптере:


public class MyOrdersAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private List<MyOrder> restaurantList;
    private Context context;


    public MyOrdersAdapter(Context context, List<MyOrder> restaurantList) {
        this.context = context;
        this.restaurantList = restaurantList;
    }


    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int position) {
        if(context != null)
            holder.data.setBackgroundResource(context.getResources().getDrawable(R.drawable.poster_infinity_war));
    }
    ...

}   

Это поможет вам предотвратить OutOfMemoryException в будущем

...