15

I'm a beginner in junit test 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

gamo
  • 1,549
  • 7
  • 24
  • 36

3 Answers3

36

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:

Simulant
  • 19,190
  • 8
  • 63
  • 98
  • I believe the new constructor should look like this: public MainActivityTest() { super(MainActivity.class); } – Mike Apr 26 '16 at 17:29
  • 1
    @Mike: I got a lot of up-votes before noticing this typo, thanks I fixed it. – Simulant Apr 26 '16 at 17:34
1

If your problem is still unresolved: You can try this annotation by adding

 @RunWith (JUnit4.class)
hpolat
  • 23
  • 6
0

For me it was the wrong structure in build.gradle.

This is the good implementation (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")
}
Endi Tóth
  • 221
  • 3
  • 15