views:

49

answers:

1

Hi, It has been decided to write some unit tests using moq etc..It's lots of legacy code c#

(this is beyond my control so cannot answer the whys of this)

Now how do you cope with a scenario when you dont want to hit the database but you indirectly still hit the database?

This is something I put together it's not the real code but gives you an idea.

How would you deal with this sort of scenario?

Basically calling a method on a mocked interface still makes a dal call as inside that method there are other methods not part of that interface?Hope it's clear

         [TestFixture]
            public class Can_Test_this_legacy_code
            {
                [Test]
                public void Should_be_able_to_mock_login()
                {
                    var mock = new Mock<ILoginDal>();
                    User user;
                    var userName = "Jo";
                    var password = "password";
                    mock.Setup(x => x.login(It.IsAny<string>(), It.IsAny<string>(),out user));

                    var bizLogin = new BizLogin(mock.Object);
                    bizLogin.Login(userName, password, out user);
                }
            }

            public class BizLogin
            {
                private readonly ILoginDal _login;

                public BizLogin(ILoginDal login)
                {
                    _login = login;
                }

                public void Login(string userName, string password, out User user)
                {
                    //Even if I dont want to this will call the DAL!!!!!
                    var bizPermission = new BizPermission();
                    var permissionList = bizPermission.GetPermissions(userName);

                    //Method I am actually testing
                    _login.login(userName,password,out user);
                }
            }
            public class BizPermission
            {
                public List<Permission>GetPermissions(string userName)
                {
                    var dal=new PermissionDal();
                    var permissionlist= dal.GetPermissions(userName);
                    return permissionlist;
                }
            }

            public class PermissionDal
            {
                public List<Permission> GetPermissions(string userName)
                {
                    //I SHOULD NOT BE GETTING HERE!!!!!!
                    return new List<Permission>();
                }
            }

            public interface ILoginDal
            {
                void login(string userName, string password,out User user);
            }

            public interface IOtherStuffDal
            {
                List<Permission> GetPermissions();
            }

            public class Permission
            {
                public int Id { get; set; }
                public string Name { get; set; }
            }

Any suggestions? Am I missing the obvious? Is this Untestable code?

Very very grateful for any suggestions.

+5  A: 

As it is now, BizLogin is not testable, as it directly instantiates BizPermission, which in turn instantiates PermissionDal, which then hits the DB.

The best solution would be to refactor BizLogin to replace the direct instantiation of BizPermission with a call to a factory (method), or Dependency Injection. It is not clear to me from your post whether you can refactor the code - if so, this is the preferred solution.

However, if refactoring is not an option, you could still try a nasty trick. This is possible in Java, I don't know C# that well, but since the two languages are fairly similar, I guess it can be possible in C# too (although I can not fill in the exact technical details).

You could replace the compiled class files of BizPermission with different mock implementations for your unit tests. This is of course risky, as you must make sure that the alternative implementations don't get mixed into your production assemblies. Also it requires a bit of messing with classpaths and stuff. So only try this if refactoring is really, absolutely out of question.

How to replace class files with test implementations

(using Java terminology - I hope it is clear enough for C# too...) The basic idea is that the runtime is looking for classes on the classpath, and it loads the first suitable class definition it finds on the classpath. So you can create a mock implementation of BizPermission in your unit test source folder, in the exact same package and with the same interface as the original. Then have it compiled into e.g. a test-classes folder (whereas your production code is compiled into e.g. classes). Now if you set up your test classpath so that test-classes is before classes, the runtime will load the fake BizPermission class when running your tests, instead of the original, when BizLogin attempts to instantiate this class.

Example of refactoring to use a factory method

public class BizLogin
{
    private readonly ILoginDal _login;

    public BizLogin(ILoginDal login)
    {
        _login = login;
    }

    protected BizPermission getBizPermission()
    {
        return new BizPermission();
    }

    public void Login(string userName, string password, out User user)
    {
        var bizPermission = getBizPermission();
        var permissionList = bizPermission.GetPermissions(userName);

        //Method I am actually testing
        _login.login(userName,password,out user);
    }
}

In test code:

public class FakeBizPermission implements BizPermission
{
    public List<Permission>GetPermissions(string userName)
    {
        // produce and return fake permission list
    }
}

public class BizLoginForTest
{
    public BizLoginForTest(ILoginDal login)
    {
        super(login);
    }

    protected BizPermission getBizPermission()
    {
        return new FakeBizPermission();
    }
}

This way you can test the critical functionality via BizLoginForTest, with minimal changes to the original BizLogin class.

An alternative would be to inject a full factory object, as mentioned in Jeff's comment. This would require a bit more code changes (possibly including in the clients of BizLogin), so it's a bit more intrusive.

Note that the prime goal of such refactorings is always to allow unit testing, not to win a prize for the beauty of your new design :-) So it is best to start with the least changes to existing code which allow you to cover the functionality with tests. Once you have the tests in place, you can refactor with more confidence towards a cleaner, better design.

Péter Török
Thanks for your reply.What you describe is exactly my problem,and I was just wondering if there was a solution avoiding refactoring which I doubt will be an option.Yours is an interesting suggestion but I dont understand what you are proposing.Is it possible to clarify with a little snippet?
Also out of curiosity.If refactoring was an option how would you refactor it?Cannot figure out how a factory method could help in this instance
A factory might help because the current `Login` method creates the `BizPermission` instance itself, suggesting that your design might not allow you to inject permission instances directly. Instead, you can inject a `BizPermissionFactory` - when testing, you would provide a factory that yields mock `BizPermission` objects.
Jeff Sternal
@devnet247, see my update.
Péter Török