2017-01-29 11 views
0

私は2つの場所間の距離を計算する関数のテストケースを作成しようとしています。Androidユニットテストは常に成功する

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); 
     } 
    } 
} 

が、これは私が実際の距離を変更すると、テストがあっても、常に渡し

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); 
    } 
} 

テストするという私のTestClassです。

答えて

1

あなたはNullPointerExceptionを取得したいと思います。

@Test(expected = NullPointerException.class) 

あなたが試験に合格するようにするには、NullPointerExceptionがテスト不合格とget RED状態を発生しないので、もしテストは、あなたがメソッドを失敗し使用することができます失敗したい場合は、NullpointerExceptoion

を期待しているので、あなたのmapScreenは、そうでない場合は、テスト合格nullですあなたは緑のステータスを取得

fail(mapScreen.method()); 

インポート:

import static org.junit.Assert.fail; 

あなたはセットアップでmapScreenのinit nullポインタ例外を取得しない場合:

@Before 
public void setUp() throws Exception { 

    place = new Place(30.050922 , 31.243414) ; 

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

私は@Test(予想= NullPointerException.class)を削除したときに取得しないようにしたい場合、私はAhmedNu'man @ nullポインタ例外 –

+0

に直面しましたNullPointerExceptionは、setUpメソッドの初期mapScreenをお願いします –

+0

今、私はこのエラーに直面しましたjunit.framework.AssertionFailedError:期待通り:<0 null>はありませんでした:<200.0> 期待:0 null 実際:200.0 –