Как проверить несколько звонков в сервис - PullRequest
0 голосов
/ 28 сентября 2019

Я пытаюсь увеличить покрытие кода на Android.Но я не могу найти правильный способ проверить этого докладчика.OnSelectContact выполняет вызов службы, а позже мой ServiceFactory.getContactService выполняет другой.Как я могу издеваться над этими звонками?

public class ContactListPresenter {

    public void onSelectContact(User user) {
        getCorrespondingContactCall(user).enqueue(new Callback <JsonElement>() {
            @Override
            public void onResponse(Call<JsonElement> call, Response<JsonElement> response) {
                switch (response.code()) {
                    case case1:
                        goToFirstActivity(user, response);
                        break;
                    case case2:
                        goToSecondActivity(user, response);
                        break;
                    default: showInvalidInput(user);
                        break;
                }
            }

            @Override
            public void onFailure(Call<JsonElement> call, Throwable throwable) {
                if (getView() != null) {
                    getView().showErrorView();
                }
            }
        });
    }

    protected Call<JsonElement> getCorrespondingContactCall(final User user) {
        return StringUtils.isValidEmail(user.getEmail())
                ? ServiceFactory.getContactService().checkContactByEmail(user.getEmail())
                : ServiceFactory.getContactService().checkContactByPhoneNumber(user.getPhoneNumber());
    }     

}

1 Ответ

0 голосов
/ 28 сентября 2019

Если можешь - исключи статические звонки.Например, путем явного введения ContactService в тестируемый класс:

public class ContactListPresenter {
    private final ContactService contactService;

    public ContactListPresenter(ContactService contactService) {
        this.contactService = contactService;
    }

    // rest of the code

    protected Call<JsonElement> getCorrespondingContactCall(final User user) {
        return StringUtils.isValidEmail(user.getEmail())
                ? contactService.checkContactByEmail(user.getEmail())
                : contactService.checkContactByPhoneNumber(user.getPhoneNumber());
    }     
}

Таким образом, в тестах вы сможете легко смоделировать Call<JsonElement>, возвращаемый вызовами contactService.

Однако, если изменение кода не вариант, у вас есть другие варианты:

  • макетировать статические вызовы с помощью Powermock

  • использует тот факт, что getCorrespondingContactCall имеет доступ protected, создавая анонимный подкласс в вашем тесте и заглушая результаты вызова getCorrespondingContactCall.Например:

public class ContactListPresenterTest {
   @Test
   public void test() {
      User user = ... // create user for test
      ContactListPresenter presenter = new ContactListPresenter() {
         @Override
         Call<JsonElement> getCorrespondingContactCall(final User user) {
            return ... // stub result of the call
         }
      };
      presenter.onSelectContact(user);
      // assert expected behavior
   }

}
...