Home:ALL Converter>Mocking and testing classes with multiple constructor parameters

Mocking and testing classes with multiple constructor parameters

Ask Time:2011-02-21T12:19:12         Author:Omar

Json Formatter

My service layer classes are setup for constructor injection. When mocking and testing these classes, how can I avoid having to pass in null for parameters I won't be using in my test?

Sample code I'm trying to avoid:

[TestFixture]
public class SomeServicesTests
{
    SomeServices _someServices;

    [SetUp]
    public void Initialize()
    {
        _someServices= new SomeServices (null, 
                                        new StubRepositoryOne(), 
                                        null, 
                                        null, 
                                        new StubRepositoryTwo(), 
                                        null, 
                                        null, 
                                        null,
                                        null);

    }

    [Test]
    public void Test_Something()
    {
        string input = "yes";
        string exptectedOutput = "no";

        string output = _someServices.SomeFunction(input); // uses StubRepositoryOne and StubRepositoryTwo
        Assert.AreEqual(exptectedOutput, output);
    }
}

Author:Omar,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/5062253/mocking-and-testing-classes-with-multiple-constructor-parameters
bryanbcook :

Adding my answer after it's already been accepted, but...\n\nThe very fact that only some of the dependencies need to be passed in for the test suggests a possible design problem. A good litmus test is that all fields in a type should be used in every method -- very hard to do this all the time -- but if you can't it means that the class can probably be broken into smaller classes with finer responsibilities. When you break them down, each class would take only the dependencies they immediately need.\n\nOn the other hand if what you're doing here is a hand-rolled service locator and you're only testing a subset of functionality, you might want to consider creating test only constructors. Such as:\n\ninternal SomeServices(IServiceOne one, IServiceTwo two)\n{\n}\n\n\nOr expose the services with getters/setters and assign accordingly. Again, the internal keyword here can be used to keep your design intent clean:\n\npublic IServiceOne One\n{\n get { return _one; }\n internal set { _one = value; }\n}\n\n\nOf course, you'd want to add the InternalsVisibleTo attribute to your code to allow your tests to access these internal methods.",
2011-02-25T08:16:37
TrueWill :

I generally validate injected parameters vs. null. I'd normally just pass in\n\nnew Mock<T>().Object\n\n\nfor these.",
2011-02-21T04:23:44
yy