Espresso testing android

2019-06-02 23:18发布

问题:

I run the tests in Android Studio, running task - "test". My test failed, my html report detailed:

   junit.framework.AssertionFailedError: Class Test has no public constructor TestCase(String name) or TestCase()
        at junit.framework.Assert.fail(Assert.java:57)
        at junit.framework.TestCase.fail(TestCase.java:227)
        at junit.framework.TestSuite$1.runTest(TestSuite.java:100)
        at junit.framework.TestCase.runBare(TestCase.java:141)
        at junit.framework.TestResult$1.protect(TestResult.java:122)
        at junit.framework.TestResult.runProtected(TestResult.java:142)
        at junit.framework.TestResult.run(TestResult.java:125)
        at junit.framework.TestCase.run(TestCase.java:129)
        at junit.framework.TestSuite.runTest(TestSuite.java:255)
        at junit.framework.TestSuite.run(TestSuite.java:250)
        at org.junit.internal.runners.JUnit38ClassRunner.run(JUnit38ClassRunner.java:84)

My source file:

    @LargeTest
public class Test extends ActivityInstrumentationTestCase2<MainActivity>{

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

    @Override
    public void setUp() throws Exception {
        super.setUp();
        getActivity();
    }

    public void testCheck(){
        onView(withId(R.id.text))
                .check(matches(withText("Hello world!")));
    }
}

回答1:

The problem is exactly what the error message says it is: You did not provide a parameter-free constructor.

Add this constructor to your test class:

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


回答2:

The prototype of a test class with espresso should be:

public class MainTest extends
        ActivityInstrumentationTestCase2<MainActivity>{

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

    @Override
    public void setUp(){
        getActivity();
    }

    @Override
    public void tearDown(){
    }

    public void test1(){

    }

    public void test2(){

    }
}