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 belowtest(){
Fun f= new Fun();
开发者_如何学C Map m =f.getaMap();
}
I want to return a custom Map at that time. How do i do it.
Thanks.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.
精彩评论