The below code lives in an instance class with no constructor, I don’t know from where to start writing unit tests for it.
E.g price is “2/9” so secondPart is 9 also the _random is an object of Random class
public string RefreshPrice(string price, out bool isUpOrDown, out bool isChanged)
{
if (string.IsNullOrEmpty(price))
{
isUpOrDown = false;
isChanged = false;
return price;
}
int secondPart;
string[] priceParts = price.Split('/');
int newPrice = 0;
if(int.TryParse(priceParts[1], out secondPart))
{
newPrice = secondPart >= 2 ? _random.Next(2, 20) : 2;
}
isUpOrDown = (newPrice > secondPart);
isChanged = (newPrice != secondPart);
secondPart = newPrice;
return string.Format("{0}/{1}", priceParts[0], secondPart);
}
So this class will have a default ctor:
If
_randomis not set up in the default ctor, you should create a helper methodgetLegacyUnderTestto set _random, either how it is set in production or have a look at this stack overflow answer for accessing privates during tests using PrivateObject.Since they’re
out, you’ll need to declare yourboolflags as part of your arrange step for the test, then you’re good to go:Now (after fixing the problems I’ve inevitably made by writing that snippet without VS in front of me) you’ll just have to vary the values of
isUpDown,isChangeandinitialPriceto cover all the possibilities you need to test and you should be good.This should be the different formats of initial price (valid, null, empty and invalid formats) combined with the different true/false combinations of those flags.