Can I replace (or override) a class definition with one of my own implementation?
Explanation:
`
class foo
{
Random r=new Random();
double bar()
{
double ans=r.NextDouble();
.....// evaluate ans
return ans;
}
}
`
What are the possible ways that I can replace implementation of Random class with another one without changing (or with minimum changes) the original code file??
Edit:
One solution is to inherit Random class and modify it... but that requires changing each Random instance with the inherited one... I do not want to modify the code, because I am just testing it!!
Edit 2:
Can I say in C#: "Each Random class in this file is MyNamespace.Random not System.Random" ??
EDIT: As ChaosPandion points out, to test the logic in the method it would be better to take a double parameter i.e. double bar(double input) { ... }, but if you have a reason to need to inject your own source of randoms, you could use one of these approaches:
You could modify bar to take a Func<double> to obtain values from:
double bar(Func<double> source)
{
double ans = source();
//evaluate ans
return ans;
}
Then you can inject your own implementation for testing, and in the main program use:
Random r = new Random();
double ans = bar(r.NextDouble);
Alternatively you could create your own IRandom interface and then implement a wrapper around the real Random class and use mocks for testing:
interface IRandom
{
double Next();
}
public class RandomWrapper : IRandom
{
private Random r = new Random();
public double Next()
{
return this.r.NextDouble();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With