1 /* 2 * Copyright (C) 2011 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.android.volley.mock; 18 19 import com.android.volley.Network; 20 import com.android.volley.NetworkResponse; 21 import com.android.volley.Request; 22 import com.android.volley.ServerError; 23 import com.android.volley.VolleyError; 24 25 public class MockNetwork implements Network { 26 public final static int ALWAYS_THROW_EXCEPTIONS = -1; 27 28 private int mNumExceptionsToThrow = 0; 29 private byte[] mDataToReturn = null; 30 31 /** 32 * @param numExceptionsToThrow number of times to throw an exception or 33 * {@link #ALWAYS_THROW_EXCEPTIONS} 34 */ 35 public void setNumExceptionsToThrow(int numExceptionsToThrow) { 36 mNumExceptionsToThrow = numExceptionsToThrow; 37 } 38 39 public void setDataToReturn(byte[] data) { 40 mDataToReturn = data; 41 } 42 43 public Request<?> requestHandled = null; 44 45 @Override 46 public NetworkResponse performRequest(Request<?> request) throws VolleyError { 47 if (mNumExceptionsToThrow > 0 || mNumExceptionsToThrow == ALWAYS_THROW_EXCEPTIONS) { 48 if (mNumExceptionsToThrow != ALWAYS_THROW_EXCEPTIONS) { 49 mNumExceptionsToThrow--; 50 } 51 throw new ServerError(); 52 } 53 54 requestHandled = request; 55 return new NetworkResponse(mDataToReturn); 56 } 57 58 } 59