godidier
godidier

Reputation: 1001

Simple Java class test with Android SDK

I would like to know how to test a simple Java class in an Android project which do not use any android SDK code, using the (JUnit based) test framework included with the android sdk. Or if I would have to use an external (JUnit) test library? Regards.

Upvotes: 1

Views: 854

Answers (2)

Philipp Sander
Philipp Sander

Reputation: 10249

Use the test framework from your android sdk. That way you can test your android code too if you want to do that later.

Testing Android

Upvotes: 2

godidier
godidier

Reputation: 1001

Thanks All, I get a clue with this link https://marakana.com/tutorials/android/junit-test-example.html, but i had to tweak it a little bit to fit my needs.

So if one want to write tests for a simple class in an android project, using the android test framework, let's say a Calculator class.

package com.example.application;


public class Calculator {

    public static int add(int a, int b){
        return a+b;
    }

    public static int sub(int a, int b){
        return a-b;
    }

}

You will have to create the following test class in your test project:

package com.example.application.tests;

import android.test.AndroidTestCase;
import com.example.application.Calculator;

public class CalculatorTest{

    public void testAdd() throws Throwable{
        assertEquals(3, Calculator.add(1,2);
    }

    public void testSub() throws Throwable{
        assertEquals(-1, Calculator.add(1,2);
    }
}

And with the command line, after compiling and installing both the main project and the test project, on the emulator (for instance), you can use the following command to test the class:

adb shell am instrument -w -e class com.example.appplication.tests.CalculatorTest com.example.application.tests/android.test.InstrumentationTestRunner

You can also use Eclipse to run the tests.

Hope this will help someone.

Upvotes: 3

Related Questions