Home > database >  C# A reference type variable that should be mocked by test classes but should not be visible outside
C# A reference type variable that should be mocked by test classes but should not be visible outside

Time:12-23

I am a beginner with C#

In my class, there is a variable ( Dictionary<string, string> ) which is an implementation detail. It should not be visible outside of that class.

My first choice was to keep it as private:

class MyClass 
{
    private Dictionary<string, string> dict = new();
}

The Unit test of this project are in a different project, so if I want to access the variable to mock it, it would not be possible.

Thus, I had to make the variable internal and use InternalsVisibleTo()

class MyClass 
{
    internal Dictionary<string, string> dict = new();
}

Now, I can mock the variable in the test class, but with this change, dict is visible to the current assembly as well. So the classes which use MyClass instance can do this:

MyClass myClass = new();
myClass.dict = new();

I can prevent it by making the variable an auto property and set the set:

class MyClass 
{
    internal Dictionary<string, string> dict {get; private set;} = new();
}

With that, other classes would not be able to reassign the same variable, but they would stil be able to update the dict:

MyClass myClass = new();
myClass.dict["key"] = "value";

How do I prevent this?

What I am looking for is, A reference type variable that should be mocked by test classes but should not be visible outside of the class that defines it.

CodePudding user response:

you can have your dictionary private, but you can create another public property which will provide read-only access. this way you see can mock it.

class MyClass
{
    private readonly Dictionary<string, string> dict = new Dictionary<string, string>();

    public IReadOnlyDictionary<string, string> Dict
    {
        get { return dict; }
    }
}

another way you can have a public method exposed which will allow access the dictionary in a very limited way

CodePudding user response:

How about a method, that returns value from dict by key? As bonus - check that key exists

class MyClass
{
    private readonly Dictionary<string, string> dict = new();
    public string DictByKey(string key) => dict.ContainsKey(key) ? dict[key] : null;
}
  • Related