我正在尝试为计算两个位置之间距离的函数编写测试用例。
var _stockByAreas = function() {
var query = function(zone) {
var queryDef = $q.defer();
// timeout is for query and response simulations
setTimeout(function() {
// ...
queryDef.resolve( {data: 'MeTe-30'} );
}, 1000);
return queryDef.promise;
}
var promises = [];
angular.forEach(storageAreas, function(zone) {
// ...
promises.push( query(zone) );
});
return $q.all(promises);
}
_stockByAreas().then(function(res) {
// res[0] resolved data by query function for storageAreas[0]
// res[1] resolved data by query function for storageAreas[1]
// ...
});
这是我要测试的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);
}
}
}
TestClass
即使改变实际距离,测试也会通过。
答案 0 :(得分:1)
因为你写了你想得到NullPointerException。
@Test(expected = NullPointerException.class)
你的mapScreen是null所以你通过了测试,因为你期望NullpointerExceptoion
如果您希望测试失败,则可以使用fail方法,因此如果未发生NullPointerException,则测试失败并获得RED状态,否则测试通过并获得GREEN状态
fail(mapScreen.method());
导入:
import static org.junit.Assert.fail;
如果你不想在setUp中获得Null指针Exception init mapScreen:
@Before
public void setUp() throws Exception {
place = new Place(30.050922 , 31.243414) ;
mapScreen = new FullMapScreen() ;//your constructor
}