Reputation: 1
I have problem with testing my method for currency exchange from API. I have no idea how to do testings to this method as I can't predict what currency rates are at the moment, they are changing every second. My teacher told me that I have to do another method that testing my first one and then Mock something. Please guys help.
public class CurrencyService {
private static HttpURLConnection conn;
private Pattern currencyPattern;
public double exchange(String currencyFrom, String currencyTo, double amount) {
currencyPattern = Pattern.compile("[A-Z]{3}");
if (!currencyPattern.matcher(currencyFrom).matches() || !currencyPattern.matcher(currencyTo).matches()) {
throw new BadPatternForCurrency("Currency FROM and TO must be for example: Dollar USD, euro EUR etc.");
}
if (amount < 0) {
throw new NoMinusValuesInAmountException("Amonut must be more than 0!");
}
DecimalFormat df = new DecimalFormat("##.##");
String adres = "https://api.apilayer.com/exchangerates_data/";
BufferedReader reader;
String line;
StringBuilder responseContent = new StringBuilder();
try {
URL url = new URL(adres + "convert?to=" + currencyTo.toUpperCase() + "&from=" + currencyFrom.toUpperCase() + "&amount=" + amount);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("apikey", "tSaLWidFRzgzO2mGNfFgVEIr2cqeWCUY");
int status = conn.getResponseCode();
if (status != 200) {
reader = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
while ((line = reader.readLine()) != null) {
responseContent.append(line);
}
reader.close();
} else {
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = reader.readLine()) != null) {
responseContent.append(line);
}
reader.close();
}
} catch (ProtocolException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
JSONObject obj = new JSONObject(responseContent.toString());
double result = obj.getDouble("result");
return result;
}
}
Upvotes: 0
Views: 458
Reputation: 870
To elaborate on @tgdavies comment:
You should better move everything starting with:
BufferedReader reader;
into a separate class, for example, ExchangeApiClient
and provide that class into your CurrencyService
via a constructor. That ExchangeApiClient
should return a string, so everything left to your service is to create a call exchangeApiClient.getResponse()
.
This way you will be able to unit-test your currency service.
The question remains how to test your ExchangeApiClient
- that can also be done. You must create a HttpConnectionFactory
and pass that factory via a constructor to your ExchangeApiClient
. You should also make it non-static. Then you can pass a mock connection, which returns mock inputStream, you can here more about that here
If you want to read something about mocking I recommend a book "Practical Unit Testing with JUnit and Mockito".
Upvotes: 1