user564159
user564159

Reputation: 51

Mock a new object creation

I am using EasyMocks.
Inside a method there is a new object created. And upon that object a method is called which returns a map. As show below

test(){
   Fun f= new Fun();
    Map m =f.getaMap();
}

I want to return a custom Map at that time. How do i do it.
Thanks.

Upvotes: 1

Views: 1249

Answers (1)

Lunivore
Lunivore

Reputation: 17602

I'm guessing from your code that you've given us a test method in which you're testing Fun and looking at the Map that Fun produces.

Dependency inject a MapFactory which creates the Map for Fun. I'm not sure about EasyMock's syntax, so mockMapFactory here is the mocked object, and it will have a method on it to create a map for you. Mock that method to produce a map, then call the method inside your class instead of using new.

test() {

    Fun f= new Fun(mockMapFactory);
    Map m =f.getaMap();
}

Take a look at the Factory design pattern, which is a really great way of allowing you to avoid calling new so that you can mock the creation of objects (and the objects themselves, if you need to). It also means that your class isn't responsible any more for deciding what kind of object it creates.

You won't be able to mock the creation of the Map inside of its factory when you test the factory. That's OK. Either test it by inspection or just check that you're getting the right kind of object out.

Upvotes: 2

Related Questions