Necronet
Necronet

Reputation: 6813

Too many dependencies in Mocking : Unit test question

I want to do a test of a Business class and I have this problem: one of the mocking objects has many dependencies to other classes such as Sites, URL, and ComplexObject.

My question is: how can I isolate my class if I have to use this method of my mock object in the method i need to test? Should I mock all of them and add them to the mocked object?

Upvotes: 4

Views: 2236

Answers (2)

IAdapter
IAdapter

Reputation: 64717

What I like to do is to create a class that has field to all outside dependecies and also static methods. for example:

public class DanceMakerDependecies{
    private URL url;

    public String getCurrentUser(){ // not static, so very easy to test
        return UserManager.currentUser().getName();
    }

    //getter and setters
}

public class DanceMaker{
     public DanceMaker(DanceMakerDependecies dep){
     ..
     }
     // you could also create default constructor with the default dependencies
}

public class DanceMakerTest{
    @Test
    void dance(){
        DanceMaker dm = new DanceMaker();
        dm.setDependecies(EasyMock.createMock(DanceMakerDependecies.class));
        //etc.
    }
}

I know that purists will prefer to just to inject everything into the class, but I find this way of testing much more simple. try it and see what you think about it(i bet its not best-pratice or design pattern, but i like it).

Upvotes: 0

Paul Rubel
Paul Rubel

Reputation: 27222

How else can you test it? It looks like you'll need to mock the dependencies. One positive aspect is that you can likely use the mocks in other classes that need testing. Note that this is a definite code smell.

Have you thought about dependency injection? If you passed in all the dependencies you could create a factory that generates a set of testing dependencies and then override just the dependencies you need for your test.

Upvotes: 5

Related Questions