Ahmed Nu'man
Ahmed Nu'man

Reputation: 23

Android unit test always passes

I am trying to write a test case for a function that's calculating the distance between two locations.

public  String calculateDistance(Place p) {


    if (p.distance > 0) {
        if (selectedPlace.distance > 1000) {
            return Long.toString(Math.round(p.distance) / 1000) + getString(R.string.km);

        } else {
            return Long.toString(Math.round(p.distance)) + getString(R.string.meter);
        }
    } else {
        Location locationA = new Location("Point A");

      locationA.setLatitude(MainActivity.lat);
      locationA.setLongitude(MainActivity.lng);
       // locationA.setLatitude(30.050922);
      //  locationA.setLongitude(31.243414);

        Location locationB = new Location("point B");

        locationB.setLatitude(p.getLatitude());
        locationB.setLongitude(p.getLongitude());

        double actualDistance = locationA.distanceTo(locationB);

        if (actualDistance > 1000) {
            return Long.toString(Math.round(actualDistance) / 1000) + " " + getString(R.string.km_away);
        } else {
            return Long.toString(Math.round(actualDistance)) + " " + getString(R.string.meter_away);
        }
    }
}

and this is my TestClass that is to be tested

public class FullMapScreenTest {
    private FullMapScreen  mapScreen ;
    private Place place ;

    // 30.050922, 31.243414
    // 30.050976, 31.243494

    @Before
    public void setUp() throws Exception {

        place = new Place(30.050922 , 31.243414) ;
    }

    @After
    public void tearDown() throws Exception {

    }
    @Test(expected = NullPointerException.class)
    public void calculateDistance() throws Exception {
  /// 30.054291, 31.242572
        double destLat = 30.054291 ;
        double desLang = 31.242572 ;
        double actualDistance = 100.00;

        Place distanation = new Place(destLat ,desLang) ;

        Assert.assertEquals(mapScreen.calculateDistance(distanation) ,actualDistance);
    }
}

The test always passes even when I change the actual distance.

Upvotes: 0

Views: 75

Answers (1)

Siavash Abdoli
Siavash Abdoli

Reputation: 1862

Because you write you want to get NullPointerException.

@Test(expected = NullPointerException.class)

your mapScreen is null so you pass the test because you expect NullpointerExceptoion

if You want test fail you can use fail method, so if NullPointerException not occurs your test fail and get RED status otherwise test pass and you get GREEN status

fail(mapScreen.method());

import:

import static org.junit.Assert.fail;

if you do not want to get Null pointer Exception init mapScreen in setUp:

@Before
public void setUp() throws Exception {

    place = new Place(30.050922 , 31.243414) ;

    mapScreen = new FullMapScreen() ;//your constructor
}

Upvotes: 1

Related Questions