我正在尝试使用Mockito测试我的应用。它是使用MVP模式构建的。这是我的合同:
public interface CityContract {
interface View {
void setData(String data);
}
interface Presenter {
boolean isViewAttached();
}
interface Model {
void getResponse(CityModel.DataCallback callback);
}
}
这是我的观点:
public class CityActivity extends AppCompatActivity implements CityContract.View {
private CityPresenter presenter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_city);
CityModel cityModel = new CityModel(city);
presenter = new CityPresenter(cityModel);
}
@Override
public void setData(String data) {
if (presenter.isViewAttached()) {
dataTextView.setText(data);
}
}
}
这是我的演示者:
public class CityPresenter implements CityContract.Presenter, CityModel.DataCallback {
private CityModel cityModel;
private CityContract.View view;
private Data data;
public CityPresenter(CityModel cityModel) {
this.cityModel = cityModel;
cityModel.getResponse(this);
}
@Override
public boolean isViewAttached() {/* ... */}
@Override
public void onResponse(Data data) {
this.data = data;
setData(data.getData());
}
public Data getData() {
return data;
}
private void setData(String data) {
view.setData(data);
}
}
这是我的模特:
public class CityModel implements CityContract.Model {
private City city;
public CityModel(City city) {
this.city = city;
}
public void getResponse(DataCallback callback) {
Callback<Data> dataCallback = new Callback<Data>() {
@Override
public void onResponse(@NonNull Call<Data> call, @NonNull Response<Data> response) {
if (response.isSuccessful()) {
Data data = response.body();
callback.onResponse(data);
}
}
};
}
public interface DataCallback {
void onResponse(Data data);
}
}
这是我的测试课程,请查看到目前为止我已经尝试过的内容:
@RunWith(MockitoJUnitRunner.class)
public class CityPresenterTest {
private CityPresenter cityPresenter;
@Mock
private CityModel cityModel;
@Mock
private Data data;
@Mock
private CityModel.DataCallback callback;
@Before
public void setUp() {
cityPresenter = new CityPresenter(cityModel);
}
@Test
public void dataAsyncValidator() {
doAnswer(invocation -> {
((CityModel.DataCallback) invocation.getArguments()[0]).onResponse(data);
return null;
}).when(cityModel).getResponse(any(CityModel.DataCallback.class));
}
}
我为回调做了一个同步答案。但是如何实现异步部分呢?预先感谢!