Hi guys I am new to Unit testing Robolectric and Mockito.
How do you code so that your Rest api calls will use mock data when running unit test?
Inside my StockFragment.java, I use SpringAndroid + Robospice to perform a Rest Api call.
Also I have a RequestListener(from Robospice) inside the fragment that updates the UI in the fragment if the request is successful or not.
Here is my fragment:
public class StockFragment extends RoboDialogFragment {
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.my_layout, container, false);
return view;
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
displayStockInfo();
}
private void displayStockInfo(){
request = new MyRequest();
request.setQuote(getStock().getSymbol());
lastRequestCacheKey = request.createCacheKey();
((BaseActivity)getActivity()).getSpiceManager().execute(request, lastRequestCacheKey, DurationInMillis.ALWAYS_EXPIRED, new MyRequestListener());
}
private class MyRequestListener implements RequestListener<PseStocksResponse> {
@Override
public void onRequestFailure(SpiceException e) {
//show toast about failure reason ...
}
@Override
public void onRequestSuccess(PseStocksResponse pseStocksResponse) {
//UPDATE UI VIEWS ...
}
}
}
Here is my Robolectric Test class.
public class StockFragmentTest {
MyRequest request;
Stock stock;
StockFragment stockFragment;
@Before
public void setUp(){
stockFragment = new StockFragment();
FragmentTestUtil.startFragment(stockInfoFragment);
FragmentTestUtil.startVisibleFragment(stockInfoFragment);
findViews();
}
public void findViews(){
quoteTextView = (TextView)stockInfoFragment.getView().findViewById(R.id.quoteTextView);
nameTextView = (TextView)stockInfoFragment.getView().findViewById(R.id.nameTextView );
...
}
@Test
public void viewShouldNotBeNull(){
assertNotNull(quoteTextView);
assertNotNull(nameTextView);
...
}
@Test
public void showDisplayedInfo(){
//TODO: Assert textview.getText() values here
}
}
One solution I am thinking is have testMode flag in the StockFragment and do some conditional statements that will return test data if true, but I think there is a better way to test.
I think I need to listen to Http requests on my Test class and catch that request then provide mock data, Im not sure though.
Aucun commentaire:
Enregistrer un commentaire