When debugging and stepping through .net code we can change the value of any variable (after instruction has been executed). Is it possible to do that, for testing purposes, programmatically?
Let's assume we need to programm of software for a device that measures gamma rays and warns if some thresholds are exceeded:
public class GeigerCounter
{
var _instrument = new Instrument();
var _warn = WarnModule();
int MeasureRadiation()
{
int measurement = _instrument.MeasureRadiation();
if (measurement > 1000){
_warn.StartWarningLvl1();
if (measurement > 2000)
_warn.StartWarningLvl2();
if (measurement > 3000)
_warn.StartWarningLvl3()
}
}
The Unit Test (MSTest v2) to test if an alarm is triggered or not would look like this:
[TestMethod]
public void measure_Test()
{
GeigerCounter gc = new GeigerCounter();
WarnModule wm = WarnModule();
gc.measure();
var warnLvl = wm.getWarnLvl();
Assert.AreEqual(Lvl0,warnLvl);
}
In the test method above we are only testing that there is no dangerous radiation is measured and since I don't want to hold some radium to test the code if an Alarm/Warning is triggered I could manually, when debugging, change the value of measurement in the MeasureRadiation() Method and of course the value in Assert.AreEqual(...,warnLvl).
Is there a way do it programmatically without changing the source code of the class GeigerCounter and WarnModule?
It would be nice if somehow we could change the value by accessing the stack or at least get the memory address of the measurement variable so we could change its value.