简体   繁体   中英

Mockito, mocking a constructor within a method of a class

Currently trying to write unit tests for a complicated system that uses a constructor within one of its method that takes itself as the parameter to inject into a database context and retrieve the correct object from the correct environment.

Trying to use Mockito to emulate this, and make it return a test object instead of it going to try and find it from the database; but i'm stumped as to how to make it work with traditional techniques and @InjectMocks + @Mock annotations.

The essence of the code is below:

public FooService{

public String fooFindObject(FooDefinition fooDef) throws FooDefinitionException{

FooFinder theFooFinders = new FooFinder(this);
Foo fooObj = theFooFinders.findFoo(fooDef);

//Logic to be tested inside here that will throw exception upon bad foo definitions

return fooObj.trackingId();

}

How could I mock this FooFinder object and make it return my own testing foo object so I can test the definition obj. Mockito is being used, and the possiblity of rewriting this code to use get/setters of the FooFinder obj is not allowed - it's not my code and I'm just there to test it.

There is a library that extends upon Mockito: PowerMockito.

It allows you to do quite some more hacking than the usual Mockito. It's pretty sweet, but the thing is, if you need PowerMockito, your design usually smells.

I would definetely refactor your design. But if you can't do this for any reason, please take a look at constructor mocking with PowerMockito:

http://benkiefer.com/blog/2013/04/23/powermockito-constructor-mocking/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM