Spring beans redefinition in unit test environment

2019-01-16 04:07发布

we are using Spring for my application purposes, and Spring Testing framework for unit tests. We have a small problem though: the application code loads a Spring application context from a list of locations (xml files) in the classpath. But when we run our unit tests, we want some of the Spring beans to be mocks instead of full-fledged implementation classes. Moreover, for some unit tests we want some beans to become mocks, while for other unit tests we want other beans to become mocks, as we are testing different layers of the application.

All this means I want to redefine specific beans of the application context and refresh the context when desired. While doing this, I want to redefine only a small portion of the beans located in one (or several) original xml beans definition file. I cannot find an easy way to do it. It's always regarded that Spring is a unit testing friendly framework so I must be missing something here.

Do you have any ideas how to do it?

Thanks.

13条回答
【Aperson】
2楼-- · 2019-01-16 04:32

I don't have the reputation points to pile on duffymo's answer, but I just wanted to chime in and say his was the "right" answer for me.

Instantiate a FileSystemXmlApplicationContext in your unit test's setup with a custom applicationContext.xml. In that custom xml, at the top, do an as duffymo indicates. Then declare your mock beans, non-JNDI data sources, etc, that will override the id's declared in the import.

Worked like a dream for me.

查看更多
登录 后发表回答