就我而言,我不得不稍微修改一下这种方法:
首先,我的TestActivity 必须与使用<action android:name="android.intent.action.MAIN" /> intent-filter 的活动处于同一级别。
然后,创建测试文件(在我的例子中是 MyTestActivityTest.java IN THE src/androidTest/java/com/your/package/name(这是一个仪器测试非常重要!!)
然后,关于测试本身:
import android.support.test.rule.ActivityTestRule;
import android.support.test.rule.UiThreadTestRule;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Before;
import org.junit.Rule;
import org.junit.runner.RunWith;
import java.util.concurrent.CountDownLatch;
@RunWith(AndroidJUnit4.class)
public class MyTestActivityTest {
@Rule
public ActivityTestRule<TestActivity> mActivityRule = new ActivityTestRule<>(TestActivity.class);
@Rule
public UiThreadTestRule uiThreadTestRule = new UiThreadTestRule();
private YourPlugin mockYourPlugin;
private CordovaWebView cordovaWebView;
private CordovaInterface cordovaInterface;
private TestActivity activity;
@Before
public void setUp() throws Throwable {
activity = mActivityRule.getActivity();
assertNotNull(activity);
final CountDownLatch signal = new CountDownLatch(1); --> this one is the important! the sync part got stucked!
Runnable action = () -> {
activity.init();
cordovaWebView = mActivityRule.getActivity().getWebView();
cordovaInterface = mActivityRule.getActivity().getInterface();
mockYourPlugin = new YourPlugin();
mockYourPlugin.initialize(cordovaInterface, cordovaWebView);
cordovaWebView.getPluginManager().addService(new PluginEntry("YourServiceName", mockBankId));
signal.countDown();// notify the count down latch, i.e release it
};
uiThreadTestRule.runOnUiThread(action);
signal.await();// wait for callback
}
@Test
public void TestBluetooth() throws JSONException {
this.mockYourPlugin.execute("echo","[]",new CallbackContext("0", cordovaWebView));
}
}
和我的 build.gradle 文件我有这个依赖项:
// JUnit 4 framework
implementation 'junit:junit:4.12'
// required if you want to use Mockito for unit tests
implementation 'org.mockito:mockito-core:2.13.0'
implementation 'org.mockito:mockito-android:2.8.47'
implementation 'com.android.support.test:rules:1.0.2'
别忘了把它也放在build.gradle 文件中:
defaultConfig {
...
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
...
}
我真的希望这会有所帮助