AS中提供了一个专门用来做单例测试的包
正常情况下我们模拟ExampleInstrumentedTest去写单例情况都是可以单例测试成功的。
MyTest.java
package com.example.myapplication;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(AndroidJUnit4.class)
public class MyTest {
@Test
public void testPrint(){
System.out.println("单例测试");
}
}
点击debug运行后都会成功的运行单例
但是我之前两天做项目时它不知道怎么了,debug单例时一直报错:
百度了一波有的说要在Edit Configuration里面做如下配置:
有的叫我在gradle里面加入依赖:
androidTestImplementation 'androidx.test:rules:1.2.0'
androidTestImplementation 'androidx.test:runner:1.2.0'
都没有得到解决。
后来自己手抽给单例测试类继承了TestCase解决了问题
package com.example.xmpp;
import android.content.Context;
import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import junit.framework.TestCase;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest extends TestCase {
@Test
public void useAppContext() {
System.out.println("111122");
// Context of the app under test.
Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
assertEquals("com.example.xmpp", appContext.getPackageName());
}
}
注意是导入==import junit.framework.TestCase;==这个包。
虽然说依然有报错,但是可以看到目前的的单例时执行了的。