2012-03-19 16 views
9

He visto un montón de publicaciones relacionadas con esto, pero ninguna parece tener el mismo problema que estoy recibiendo. GetBusinessRulesTask extiende AsyncTask. Cuando ejecuto esto en un caso de prueba de unidad, nunca se llama a onPostExecute(). Sin embargo, si uso el código de cliente real, entonces se llama onPostExecute() cada vez. No estoy seguro de lo que estoy haciendo mal aquí.AsyncTask onPostExecute() no llamado en la Unidad de Caso de Prueba

Caso

prueba:

package com.x.android.test.api; 

import java.util.concurrent.CountDownLatch; 

import android.test.ActivityInstrumentationTestCase2; 
import android.test.UiThreadTest; 
import android.widget.Button; 

import com.x.android.api.domain.businessrule.BusinessRules; 
import com.x.android.api.exception.NetworkConnectionException; 
import com.x.android.api.tasks.GetBusinessRulesTask; 
import com.x.android.test.activity.SimpleActivity; 

public class GetBusinessRulesTaskTest 
    extends 
     ActivityInstrumentationTestCase2<SimpleActivity> { 
SimpleActivity mActivity; 
Button mButton; 

public GetBusinessRulesTaskTest() { 
    super("com.x.android.test.activity", SimpleActivity.class); 
} 

@Override 
protected void setUp() throws Exception { 
    super.setUp(); 
    mActivity = this.getActivity(); 
    mButton = (Button) mActivity 
      .findViewById(com.x.android.test.activity.R.id.b1); 
} 

public void testPreconditions() { 
    assertNotNull(mButton); 
} 

@UiThreadTest 
public void testCallBack() throws Throwable { 
    final CountDownLatch signal = new CountDownLatch(1); 
    final GetBusinessRulesTask task = (GetBusinessRulesTask) new GetBusinessRulesTask(
      new GetBusinessRulesTask.Receiver<BusinessRules>() { 
       @Override 
       public void onReceiveResult(BusinessRules rules, Exception e) { 
        assertNotNull(rules); 
        assertNull(e); 
        signal.countDown();// notify the count down latch 
       } 
      }); 
    task.start(mActivity.getApplicationContext()); 
    try { 
     signal.await();// wait for callback 
    } catch (InterruptedException e1) { 
     fail(); 
     e1.printStackTrace(); 
    } 
} 
} 

OnPostExecute:

@Override 
protected void onPostExecute(AsyncTaskResponse<O> response) { 
    Log.d(TAG, "onPostExecuted"); 
    if (mReceiver != null) { 
     mReceiver.onReceiveResult(response.getResponse(), response.getException()); 
    } 
} 

DoInBackground:

@Override 
protected AsyncTaskResponse<O> doInBackground(I... params) { 
    Log.d(TAG, "doInBackgroundr"); 
    try { 
     Uri uri = createUri(params); 
     mBaseRequest = new GetLegacyRequest(uri); 
     String json = mBaseRequest.executeRequest(); 
     O response = deserializeJson(json); 
     Log.d(TAG, "Returning AsyncTaskResponse"); 
     return new AsyncTaskResponse<O>(response, null); 
    } catch (Exception e) { 
     Log.e(TAG, "Error", e); 
     /* 
     AsyncTaskResponse<O> maintenance = ReadBusinessControlledPropertiesTask.blockingCall(mServiceLocatorUrl); 
     if(maintenance.getException() == null) { 
      MaintenanceException mExcep = new MaintenanceException(maintenance.getResponse()); 
      if (mExcep.isUnderMaintenance()) 
       return new AsyncTaskResponse(null,mExcep); 
     }*/ 
     return new AsyncTaskResponse<O>(null, e); 
    } 
} 

método Start()

public AsyncTask<Void, Void, AsyncTaskResponse<BusinessRules>> start(
     Context context) throws NetworkConnectionException { 
    super.start(context); 
    Log.d(TAG, "start"); 
    return execute(); 
} 

ENCONTRÓ EL PROBLEMA. No hagas tu AsyncTask final y ponlo dentro del ejecutable.

La solución:

public void testCallBack() throws Throwable { 
    final CountDownLatch signal = new CountDownLatch(1); 
    // Execute the async task on the UI thread! THIS IS KEY! 
    runTestOnUiThread(new Runnable() { 
    @Override 
     public void run() { 
      try { 
       GetBusinessRulesTask task = (GetBusinessRulesTask)new GetBusinessRulesTask(new GetBusinessRulesTask.Receiver<BusinessRules>() { 
          @Override 
          public void onReceiveResult(
            BusinessRules rules, Exception e) { 
           assertNotNull(rules); 
           assertNull(e); 
           signal.countDown();// notify the count downlatch 
          } 
         }); 
       task.start(mActivity.getApplicationContext()); 
      } catch (Exception e) { 
       Log.e(TAG, "ERROR", e); 
       fail(); 
      } 
     } 
    }); 
    try { 
     signal.await();// wait for callback 
    } catch (InterruptedException e1) { 
     fail(); 
     e1.printStackTrace(); 
    } 
} 
+0

lo que está pasando en este método 'start' (' task.start (mActivity.getApplicationContext()); ')? ¿Simplemente configura algunas cosas y llama a 'ejecutar'? – kabuko

+0

Agregué más código arriba. – LowDev1

+0

Lo mejor sería que publicara su respuesta como una respuesta real, y no solo dentro de la pregunta. – PearsonArtPhoto

Respuesta

5

FOUND el tema. No hagas tu AsyncTask final y ponlo dentro del ejecutable.

La solución:

public void testCallBack() throws Throwable { 
    final CountDownLatch signal = new CountDownLatch(1); 
    // Execute the async task on the UI thread! THIS IS KEY! 
    runTestOnUiThread(new Runnable() { 
     @Override 
     public void run() { 
      try { 
       GetBusinessRulesTask task = (GetBusinessRulesTask)new GetBusinessRulesTask(new GetBusinessRulesTask.Receiver<BusinessRules>() { 
          @Override 
          public void onReceiveResult(
            BusinessRules rules, Exception e) { 
           assertNotNull(rules); 
           assertNull(e); 
           signal.countDown();// notify the count downlatch 
          } 
         }); 
       task.start(mActivity.getApplicationContext()); 
      } catch (Exception e) { 
       Log.e(TAG, "ERROR", e); 
       fail(); 
      } 
     } 
    }); 
    try { 
     signal.await();// wait for callback 
    } catch (InterruptedException e1) { 
     fail(); 
     e1.printStackTrace(); 
    } 
} 
+0

Tuve exactamente el mismo problema y esto lo solucionó. ¿Alguien puede explicar por qué? – tronbabylove

+1

El TestCase se ejecuta en un subproceso separado del subproceso de interfaz de usuario real de la aplicación. Por lo tanto, para obtener la devolución de llamada en el subproceso correcto, debe suceder en un subproceso que cree. Entonces, en el código anterior obtienes la devolución de llamada en el mismo hilo que el ejecutable que creas. – LowDev1