For an application that retrieves live stock prices I find my unit test assertions returning false negatives due to price fluctuations between two calls that populate variables which hold the expected and actual test values.
While this is to be expected, I would love to hear different approaches as to how work around this issue. My initial thoughts was to allow for a margin of fluctuation (~2% difference between retrieved stock prices)
This is the code making the Web request to Yahoo in order to retrieve a stock price.
public string makeWebRequest(string stockSymbol, string dataRequestID)
{
string request = webClient.DownloadString("http://finance.yahoo.com/d/quotes.csv?s=" + stockSymbol +
"&f=" + dataRequestID).Replace("\r\n", "").Replace("\"", "");
if (request.Equals("N/A") || request.Equals("0"))
return "0.00";
return request;
}
public string getPrice(string stockSymbol)
{
return makeWebRequest(stockSymbol, "l1");
}
This is the unit test which makes a “hard coded” (known to be successful) web request for the stock price and assigning the result to the expected variable. Afterwards, perform another call in order the retrieve the price only this time using the applications object.function then assigning it to the actual variable.
The delta between calls is of 300ms
[TestMethod]
public void getPrice()
{
string expected = request.DownloadString("http://finance.yahoo.com/d/quotes.csv?s=" + testSymbol + "&f=l1").Replace("\r\n", "").Replace("\"", "");
string actual = yahoo.getPrice(testSymbol);
Assert.AreEqual(expected, actual);
}
Any Suggestions? Or should I just learn to live with it?
Save what your call to server receives and then write unit test that verifies that you can parse that string.
You can also write a test that verifies that you try to hit right url for specified symbol. Those would be unit tests. Your is integration test.