supriya
supriya

Reputation: 11

Unit testing in android studio

I am using newest version of android studio gradle plugin 1.2.3. I am unable to understand how to create unit tests in it; all the available answers are for older version of android. Help me.

Upvotes: 0

Views: 1525

Answers (1)

Rich
Rich

Reputation: 1055

first of all you need a different folder structure for your unit tests. android studio automatically generats the androidTest folder for instrumentation tests, but you can't put your unit tests in there. so you have to create a "test" folder:

- src
  -- androidTest //for instrumentation tests
  -- main        //source code
  -- test        //for unit tests

use the same package structure for your tests as for the class you want to test.

you can switch in your build variants of android studio between Android Instrumentation Tests and Unit Tests.

enter image description here

depending on your selection test or androidTest folder will be show in your project tab.

finally you have to add junit to your dependencies in gradle:

dependencies {
  testCompile 'junit:junit:4.12'
}

the test classes in your test folder can for example look like this:

package package.of.class.to.test

import org.junit.Before;
import org.junit.Test;
...
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;

public class TestSomething{

  @Before
  public void setup(){
    // test setup
  }

  @Test
  public void testSomething(){
    // your unit tests like these simple examples
    assertThat(anyBooleanResult, is(expectedBooleanResult));
    assertEquals(anyIntResult, expectedIntResult);
  }
}

for further information you can also take a look on this thread.

Upvotes: 1

Related Questions