Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
664 views
in Technique[技术] by (71.8m points)

unit testing - How to override the behavior of Spring @Autowired

A little background:

I am Using Spring 2.5, and specifically Spring IOC and annotations.

I am using @Autowired in my code (the Autowiring is done by type) and use @Component for exposing classes to the automatic wiring.

The situation described below arose while I tried to test my code.

Now to the problem:

Note: I use a different Spring Context for the Test environment.

I have a class FOO which is @Autowired but in the test context I want to use a different class of the same type MockFoo (extends FOO).

The Spring setup of course fails automatically due to multiple options for the Dependency Injection of the FOO class (both FOO and MockFOO comply to the Type check).

I am looking for a way to inject the test bean instead of the original bean.

I expected Spring to allow using the Context configuration file to override a bean injection or to order Spring not to autowire a specific bean.

BUT

All these options seem to exists only for the beans which were originally defined in the Spring Context Configuration file.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use ReflectionTestUtils to manually set the Mock in place of the autowired dependency (for that purpose your mock must not be spring managed, so that no ambiguity exists)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...