简体   繁体   English

错误“在 Junit 测试中没有公共 TestCase(String name) 或 TestCase()

[英]Error "has no public TestCase(String name) or TestCase() in Junit test

I'm a beginner in junit test android.我是junit测试android的初学者。 I'm following this tutorial but get this error我正在关注本教程,但收到此错误

junit.framework.AssertionFailedError: Class com.example.projectfortest.test.MainActivityTest has no public constructor TestCase(String name) or TestCase()
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:191)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:176)
at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:554)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1701)

This is my code:这是我的代码:

public class MainActivityTest extends
        ActivityInstrumentationTestCase2<MainActivity> {

    private MainActivity mMainActivity;
    private TextView mFirstTestText;
    private String expected, actual;

    public MainActivityTest(Class<MainActivity> activityClass) {
        super(activityClass);
    }

    @Override
    protected void setUp() throws Exception {
        super.setUp();

        mMainActivity = getActivity();
        mFirstTestText = (TextView) mMainActivity.findViewById(R.id.txt1);

        expected = mMainActivity.getString(R.string.txt1_test);
        actual = mFirstTestText.getText().toString();
    }

    public void testPreconditions() {
        assertNotNull("mMainActivity is null", mMainActivity);
        assertNotNull("mFirstTestText is null", mFirstTestText);
    }

    public void testMyFirstTestTextView_labelText() {
        assertEquals(expected, actual);
    }
}

I didn't see anything wrong in my code.我的代码中没有发现任何错误。 Please help请帮忙

As the Exception says add a default Constructor to your Class.正如异常所说,将默认构造函数添加到您的类。 This is needed for the initialisation by the testing framework.这是测试框架初始化所必需的。 Replace your constructor:替换您的构造函数:

public MainActivityTest(Class<MainActivity> activityClass) {
    super(activityClass);
}

by the following:通过以下方式:

public MainActivityTest() {
    super(MainActivity.class);
}

This constructor has no arguments as needed by the framework and showing in the code listing of your tutorial :此构造函数没有框架所需的参数,并显示在教程的代码列表中:

如果您的问题仍未解决:您可以通过添加来尝试此注释

 @RunWith (JUnit4.class)

For me it was the wrong structure in build.gradle.对我来说,它是 build.gradle 中的错误结构。

This is the good implementation (build.gradle.kts):这是一个很好的实现(build.gradle.kts):

defaultConfig {
    testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
}

dependencies {
   androidTestImplementation("junit:junit:4.13.1")
   androidTestImplementation("androidx.test:runner:1.2.0")
   androidTestImplementation("androidx.test:rules:1.2.0")
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM