开发者

Mocking my custom dependencies with Spring

Is is possible to declare mocks using some mocking framework for my own classes declaratively with Spring? I know there are some standard mocks available in Spring, but I'd like to be able to mock out my own classes declaratively too.

Just to check I'm not going about this 开发者_如何转开发the wrong way: the idea is to have a pair of JUnit test and Spring config for each integration test I want to do, mocking everything except the specific integration aspect I'm testing (say I had a dependency on two different data services, test one at a time) and minimising the amount of repeated Java code specifying the mocks.


I did it using special context.xml that included the real XML and overwrote definition of the special beans. Id'd be happy to know that there is better and smarter solution but this one worked fine for me.


Seriously - you really dont want to be doing that.

I have seen a number of projects that attempt to do this and i promise that you will end up with

A huge number of spring files, each one slightly different, but you don't know what and why. Spaghetti code, because the "declarative" definition doesn't allow to figure out that your objects are doing too much, or doing it with the wrong collaborators.

In the system case, there are a number of points at which you can stub out external services...

I would recommend that you read GOOS - It devotes a book to answering this kind of question.

http://www.growing-object-oriented-software.com/


If there is only a few beans that you want to change, and you want to change them for all tests, the you could have a look at the @Primary annotation.

You have to annotate the special class for the tests with @Primary - then it will "override" the real class. -- But use this only if you want to do it for all tests.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜