daxnet
daxnet

Reputation: 103

Is it possible to mock a local-initialized object with MOQ?

I have the following code:

public class DB
{
    public virtual int GetNumbers()
    {
        return 42;
    }
}

public interface ITestable
{
    int TestMethod();
}

public class Testable : ITestable
{
    public int TestMethod()
    {
        DB db = new DB();
        return db.GetNumbers() + 20;
    }
}

Now I want to use MOQ to create a mock of DB, so that every time the DB is created and initialized (Just like in the Testable.TestMethod), it will use the mocked DB instance.

For example, maybe I can setup the DB Mock so that for all DB's instance, when the GetNumbers method is called, it will return 12 instead of 42. Such that the Testable.TestMethod will return 32, instead of 62.

I want to know is it possible for MOQ to handle such kind of scenario? Actually I know that TypeMock Isolator and Microsoft Fakes Framework can achieve this. And I also don't like to go with the "Test Driven Development" approach (Which means I need to adjust my design).

Upvotes: 2

Views: 1484

Answers (1)

k.m
k.m

Reputation: 31454

No, you cannot mock that with Moq nor any other dynamic proxy based framework. You don't need TDD (which has little to do with your problem) - what you should be looking at instead is Dependency Injection (this will alter your design).

Testable version of your code would require factory and abstraction over DB object, for example:

public class Testable : ITestable
{
    private readonly Func<IDb> dbFactory;  

    public class Testable(Func<IDb> dbFactory)
    {
        this.dbFactory = dbFactory;
    }


    public int TestMethod()
    {
        var db = dbFactory();
        return db.GetNumbers() + 20;
    }
}

With Moq, this is the most common approach to such problems. You'll have to resort to paid tools if you want to stick with your current design.

Upvotes: 2

Related Questions