25


I am working with Android Studio and I need to add a unit tests to my project.
I read various tutorials, but nothing hepled me.
My problem is:
TestXMLParser.java:

public class TestXMLParser extends ActivityInstrumentationTestCase2<HomePageActivity> {

public TestXMLParser(Class<HomePageActivity> activityClass) {
    super(activityClass);
}

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

    //Controller.init((Activity)getContext());
}

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

public void testTrue() throws Exception {
    assertTrue(true);
}
...
}

When I run it, I see this message:

junit.framework.AssertionFailedError: Class cz.cvut.kosapp.jUnitTests.TestXMLParser has no public constructor TestCase(String name) or TestCase()
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:190)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:175)
at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:555)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1661)

I really do not know why. Other jUnit tests works well, for example when I use:

public class TestXMLParser extends AndroidTestCase { ...

in header, this works and tests are running correctly.
But I need use the Context (as a Activity) to run other code (in Controller class).

Do you have any idea how fix it?
Thank you for your comments.

hoss
  • 2,430
  • 1
  • 27
  • 42
dusanjencik
  • 293
  • 3
  • 5

1 Answers1

45

You need to add either a default constructor or a constructor which takes a String as a parameter. Adding the following default constructor with a call to the base class constructor should work:

public TestXMLParser() {
    super(HomePageActivity.class);
}
p e p
  • 6,593
  • 2
  • 23
  • 32
  • Thanks for comment, but it is not correct answer. This constructor is not avalable in ActivityInstrumentationTestCase2. – dusanjencik Jul 12 '13 at 06:33
  • 9
    You are correct - ActivityInstrumentationTestCase2 doesn't expose a default constructor. Instead, you make a default constructor for your class and then call super with valid parameters for one of the ActivityInstrumentationTestCase2 constructors - one of them which accepts a class - and you pass in the class under test. I found something similar here as well: http://stackoverflow.com/questions/2346734/trying-to-run-android-junit-tests-in-eclipse-fails – p e p Jul 12 '13 at 13:35
  • 2
    Android Studio moves so quickly that half of the published books that you have spent money on and a lot of the internet examples simply don't work. – nimbusgb Mar 29 '15 at 11:01