Linked Questions

Popular Questions

How to Mock a class having no default construtor

Asked by At

I want to mock a class having no default constructor and call a method inside it. This method calls another method of the same class. I want to setup this second method to return a value ad execute rest of the part of first method to test some results.

public void TestFunction(){
    int d=0;
    var mockObject = new Mock<Foo>(){MockBehaviour.Default, p, q}; //p and q are parameters for Foo constructor

Class Foo{
    public Foo(int x,int y){}

    public virtual int func1(){

    public virtual int func2(){}

I am mocking Foo because I don't want func2() to be executed when I test func1(). Hence I setup the mockObject to return a value for func2() without executing it when func1() calls func2().

When I run this test case I get exception "System.NotSupportedException : Parent does not have a default constructor. The default constructor must be explicitly defined."

If I see the mockObject while debugging the test case, mockObject.Object is not getting initialized. I am new to unit testing and Mock. Can someone help me about where I am going wrong.

Related Questions