chevron-thin-right chevron-thin-left brand cancel-circle search youtube-icon google-plus-icon linkedin-icon facebook-icon twitter-icon toolbox download check linkedin phone twitter-old google-plus facebook profile-male chat calendar profile-male
0 votes
Hi

I am trying to use AssignField to set the value of a variable that is declared within the method I wish to test. It is existing code and refactoring is being avoided wherever possible.

As in the simplified example below I can set a class level variable with no problems, but trying to set the method level variable fails when attempted as shown. I've made further attempts but I can't find a way to make it work, am I missing something obvious?

Thanks for your help,
Andy

public class ClassBeingTested
{
    int a = 0;

    public void MethodBeingTested()
    {
        int b = 0;
    }
}

[TestMethod]
[Isolated]
public void TestMethod()
{
    Mock ctt = MockManager.Mock<ClassBeingTested>();
    
    ctt.AssignField("a", 1);
    ctt.AssignField("b", 1);  // This line causes the error "Type ClassBeingTested does not contain a definition for b"
}
asked by andythorn (6.1k points)

1 Answer

0 votes
Hi Andy,

AssignField is implemented using reflaction hence is limited to the abilities of reflactions.

public void MethodBeingTested()
{
    int b = 0;
}

Is declared inside a method so it is created after you call MethodBeingTested().

It means that at the time that you write:
ctt.AssignField("b", 1);

b doesn't exist in the memory so you can't touch it with reflaction.

You can send us the code under test along with a short brief of what you want to test, and we'll try to find a way to do it.
answered by alex (18k points)
...