classAddressRetriever { @Throws(IOException::class, ParseException::class) funretrieve(latitude: Double, longitude: Double): Address { val parms = String.format("lat=%.6flon=%.6f", latitude, longitude) val response: String = HttpImpl().get("http://open.mapquestapi.com/nominatim/v1/reverse?format=json&$parms") val obj: JSONObject = JSONParser().parse(response) as JSONObject val address: JSONObject = obj.get("address") as JSONObject val country = address.get("country_code") as String if (country != "us") { throw UnsupportedOperationException("cannot support non-US addresses at this time") } val houseNumber = address.get("house_number") as String val road = address.get("road") as String val city = address.get("city") as String val state = address.get("state") as String val zip = address.get("postcode") as String return Address(houseNumber, road, city, state, zip) } }
AddressRetriever 클래스에 대한 테스트는 어떻게 작성해야할까?
코드의 길이는 길지만, 조건문은 하나이기때문에 상대적으로 쉬워보인다.
Http 프로토콜을 호출하는 HttpImpl 클래스는 아래와 같다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
classHttpImpl : Http { @Throws(IOException::class) overrideoperatorfunget(url: String): String { val client: CloseableHttpClient = HttpClients.createDefault() val request = HttpGet(url) val response: CloseableHttpResponse = client.execute(request) returntry { val entity: HttpEntity = response.getEntity() EntityUtils.toString(entity) } finally { response.close() } } }
val parms = String.format("lat=%.6flon=%.6f", latitude, longitude)
val response: String? = http["http://open.mapquestapi.com/nominatim/v1/reverse?format=json&$parms"] val obj: JSONObject = JSONParser().parse(response) as JSONObject val address: JSONObject = obj.get("address") as JSONObject val country = address.get("country_code") as String
if (country != "us") { throw UnsupportedOperationException("cannot support non-US addresses at this time") }
val houseNumber = address.get("house_number") as String val road = address.get("road") as String val city = address.get("city") as String val state = address.get("state") as String val zip = address.get("postcode") as String return Address(houseNumber, road, city, state, zip) } }
이제 AddressRetriever 클래스는 Http 인터페이스 구현체를 외부로부터 주입받는다.