-1

I have class which calls a static class, the static class basically is wrapper for another class. I know i can't mock/ioc static classes but can do this for the non-static class?

below is a sample of my code structure

namespace lib.CanModify
{
    public class Something
    {
        public void method()
        {
            var obj = lib.CanNotModify.StaticClass.DoSomething();


        }
    }

}
namespace lib.CanNotModify
{
    public static class StaticClass
    {
        public static Node DoSomething()
        {
            /*The class i want to mock!*/
            Node node = new Node(10);
            return node;

        }
    }
}

please advice a way to mock the node class via mstest

user1410696
  • 136
  • 7

2 Answers2

2

the short answer is no!

You cannot mock concrete implementations of classes. You can only create instances of classes, you can only mock interfaces or base classes. A mock pretends to be a concrete class by implementing the properties of the interface or base class using inheritance. basically creating a new concrete instance of the class on the fly.

If you change your structure to:

public class Node() : INode

Then you could mock this:

var moqNode = new Mock<INode>();

(this is moq syntax btw)

you would then need to change your variable to type INode

INode node = new Node(10);

and then you'd actually also need to inject your dependancy:

public static Node DoSomething(INode node)
        {

            return node;

        }

which would make a farce of the entire thing......?!

Liam
  • 27,717
  • 28
  • 128
  • 190
2

You could create a StaticClassWrapper and an interface IStaticClass, then inject IStaticClass into your method.

Then you can easily mock IStaticClass

namespace lib.CanModify
{
    using lib.CanNotModify;

    public class Something
    {
        public void method()
        {
            method(new StaticClassWrapper());
        }

        public void method(IStaticClass staticClass)
        {
            var obj = staticClass.DoSomething();
        }
    }

    public interface IStaticClass
    {
        Node DoSomething();
    }

    public class StaticClassWrapper : IStaticClass
    {
        public Node DoSomething()
        {
            return lib.CanNotModify.StaticClass.DoSomething();
        }
    }

}

This is similar to how the ASP.NET MVC project made classes such as System.Web.HttpRequest mockable

Patrick McDonald
  • 64,141
  • 14
  • 108
  • 120