1

I am attempting to write automated tests for my projects.

I have no control over how the following code has been written and have no ability to modify this code:

Public Class IAmASignleton
  Private Shared ReadOnly _Instance As ISomeInterface

  Shared Sub New()
      _Instance = New ConcreteVersionOfInterface()
  End Sub
End Class

Is there anyway for me to overwrite/replace the instance property in this class so that I can create a test version of this interface that would be used in place of the hard coded class when I am in my Test project?

Can I use a tool to intercept the Calls to this class and insert my own?

Any other way to approach replacing the ConcreteVersionOfInterface with my own class?

TDDdev
  • 1,490
  • 1
  • 17
  • 18
  • Take a look at this C# example: http://stackoverflow.com/questions/934930/can-i-change-a-private-readonly-field-in-c-sharp-using-reflection – rskar Jul 29 '14 at 22:49
  • Unfortunately this example does not work. They are able to create an instance of the class they are setting the private variable on. Because IAmASignleton has a Shared constructor, I can not get an instance of that Class. If I try to use the Shared Object it will not compile with an exception of: only member access expression can start an invocation statement. – TDDdev Jul 30 '14 at 12:58

2 Answers2

2

Try something like this:

    GetType(IAmASignleton).GetField("_Instance", _
        Reflection.BindingFlags.NonPublic Or Reflection.BindingFlags.Static _
        ).SetValue(Nothing, New ConcreteVersionOfInterface_Test)

(I did in my own "toy project", using your example IAmASignleton etc., and it worked there.)

rskar
  • 4,607
  • 25
  • 21
  • I am not sure what x is defined as is. It appears that in my current situation if I try to instansiate a new instance of IAmASignleton so that I can use that for x it breaks during its creation. If that is the case, then that would be another problem altogether and this would be the correct answer. – TDDdev Jul 30 '14 at 17:21
  • Instead of x, use `Nothing`. Anyway, that works in my toy project. – rskar Jul 30 '14 at 18:14
  • After continuing along the path, this is the correct method to accompolish what I was looking for. Thank you. – TDDdev Jul 30 '14 at 18:14
0

According to the documentation, you can't do that:

You can assign a value to a ReadOnly variable only in its declaration or in the constructor of a class or structure in which it is defined.

Alireza
  • 4,976
  • 1
  • 23
  • 36
  • I understand this should not be done. Unfortuantely the ConcreteVersionOfInterface calls to a Server, a Server that my Test Project does not have access to. So I am hoping to find a way to fake that Class or Replace that class in Test, so that I can keep everything in Memory – TDDdev Jul 30 '14 at 12:49