NUnit Mocking not working for Singleton Method

前端 未结 3 806
耶瑟儿~
耶瑟儿~ 2020-12-20 00:31

Bear with me, I\'m new to NUnit. I come from the land of Rails, so some of this is new to me.

I have a line of code that looks like this:

var code =         


        
3条回答
  •  清歌不尽
    2020-12-20 01:23

    Seems there is a kind of solution for this using reflection, or maybe I totally misunderstood this.

    It is discussed here: http://www.geekbeing.com/2010/05/23/how-to-unit-test-singleton-hack-in-c

    Could it really works?

    public class TestableSingleton : SingletonClass
    {
      public TestableSingleton ()
      {
        FieldInfo fieldInfo = typeof(SingletonClass)
            .GetField("_instance",
            BindingFlags.Static | BindingFlags.NonPublic);
        fieldInfo.SetValue(Instance, this);
      }
    }
    

    Project availabe on https://github.com/rbabreu/TestableSingleton

    Actually I could not compile it on Visual Studio since the SingletonClass would have a private constructor. If someone get it to work would be great to avoid the overhead of adapter pattern.

提交回复
热议问题