3

In my C# project I have a dependency on a 3rd party library. Now I want to write an automated acceptance test for my project. However to invoke the test I need an instance of a class from the 3rd party library. Using reflection I managed to set the values as I needed them apart from one.

Here is the relevant class that I am having the issue with:

public class SystemResults
{
    // There must be something like this. However I cannot see it as it is private.
    private List<Positions> xyz = new List<Positions>();

    public IList<Positions> Positions
    {
        get
        {
            return xyz;
        }

        // This property does not have a set method
    }
}

Here is what I have tried so far:

private void InitSystemResults(Type trueSysResType, SystemResults sysRes)
{
    List<Position> positions = ImporterTools.GetPositions(PositionsCsv);
    trueSysResType.GetProperty("Positions").SetValue(sysRes, positions); // ==> Here I get an exception
}

When I invoke the SetValue() method the following exception is thrown.

System.ArgumentException : Property set method not found.

From this information I figured out, that the class must look as I described above.

Now I would like to proceed with this some how. Has anybody an idea how I can achieve that when I access sysRes.Positions my positions are returned by the get method? Or is there a way to change the get method?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Konstantin
  • 461
  • 1
  • 5
  • 13

2 Answers2

2

You can use BindingFlags.NonPublic,

FieldInfo[] fields = typeof(SystemResults).GetFields(
                         BindingFlags.NonPublic |
                         BindingFlags.Instance).ToArray(); // gets xyz and the other private fields

List<int> testResults = new List<int>() { 1,23,4,5,6,7}; // list of integer to set

SystemResults sysres = new SystemResults(); // instance of object
fields[0].SetValue(sysres, testResults); // I know that fields[0] is xyz (you need to find it first), 
// sets list of int to object

enter image description here

Hope helps,

Berkay Yaylacı
  • 4,383
  • 2
  • 20
  • 37
0

{get;} only properties can have a backing field but Positions may be returning something completely different (not a value of a backing field, but maybe a result of a function).

Your code could accept ISystemResults which you can mock and in real code you could have a class SystemResultsFacade which internally calls the 3rd party code.

tymtam
  • 31,798
  • 8
  • 86
  • 126