我想在android中对异步方法进行单元测试。
我在MainActivity
中有一个异步回调方法。代码在下面分享。
MainActivity.java
public class MainActivity extends AppCompatActivity implements IcallBacks{
Object object;
ResultClass resultClass;
Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button=findViewById(R.id.button1);
button.setVisibility(View.INVISIBLE);
resultClass = new ResultClass(this,10);
}
@Override
public void callBack(Object object) {
this.object=object;
Log.d("CallBack", "callBack: ");
}
}
Result.java 是提供asynchronous callback
的类。该代码在下面分享。
Result.java
public class ResultClass {
IcallBacks icallBacks;
public ResultClass(final IcallBacks icallBacks, int a) {
this.icallBacks=icallBacks;
Log.d("CallBack", "ResultClass: Constructor");
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(5000);
icallBacks.callBack(this);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
}
接口类也在
下面共享IcallBacks.java
public interface IcallBacks {
public void callBack(Object object);
}
答案 0 :(得分:0)
首先,你的MainActivity依赖于你的ResultClass,所以如果要测试MainActivity的逻辑,你应该将它们分离,你需要注入你的ResultClass而不是在onCreate方法中直接创建,你可以使用Dagger库来帮助你,或者通过Intent传递RunClass实例,样本使用后者。
在进行注入以解耦它们之后,我建议在RunClass中添加一个方法来启动异步工作,例如start(IcallBacks callback),这是用于模拟方法回调逻辑:
public class MainActivity extends Activity implement IcallBacks {
@Override
protected onCreate(Bundle) {
// again, use Dagger is better
Bundle b = getIntent().getExtras();
RunClass async = b.getSerialible("callback");
.... other code
async.start(this);
}
}
@RunWith(AndroidJUnit4.class)
public class UnitTest {
@Rule
public ActivityTestRule<MainActivity> mActivityRule = new ActivityTestRule<>(MainActivity.class, true, false);
private RunClass mAsync;
private Bundle startupData;
@Before
public void setup(){
mAsync = Mockito.mock(RunClass.class);
startupData = new Bundle();
// suppose RunClass implement Serializable, you should use Dagger for better
startupData.putSerializable("callback", mAsync);
}
@Test
public void callbackTest(){
when(mAsync.start(any(IcallBacks.class).thenAnswer(i -> {
IcallBacks callback = i.getArgument(0);
callback.callBack(mAsync);
return null;
});
// start your activity
mActivityRule.launchActivity(new Intent().putExtras(startupData));
}