简体   繁体   中英

How do I unit test a Spring 4 DAO method with Spring Security?

I had some unit tests for the DAO layer of a Spring 4 MVC application. Then I added Spring Security to certain methods in my controllers, and the DAO's they use.

I figured out how to make the @WithMockUser annotation work in the controller tests, but I'm stumped on the DAO tests. The exception I get on every dao test is:

java.lang.IllegalStateException: Failed to load ApplicationContext
....
Caused by: java.lang.IllegalArgumentException: An AuthenticationManager is required

I have these annoations at the start of the DaoTest:

@TestExecutionListeners({ WithSecurityContextTestExecutionListener.class })
@ContextConfiguration(classes = DaoConfig.class)

The @ContextConfiguration is the same as in the actual code; I've suggestions to make it different, but nothing concrete. How do I unravel this? I'm also hoping there's a way to do it without using org.springframework.web.* or org.springframework.test.web.* classes, since this should be 'underneath' the whole web tier.

In general it's not a good idea to test too many things at once. With a unit test you want to test one thing and one thing only. My advice would be to not have Spring Security load at all when your DAO unit tests run. You should be able to make your DAO unit test class extend some kind of AbstractTest class that loads a separate applicationContext-test.xml or Java Config that does not include Spring Security at all. That should allow your unit tests to not have to pierce some security layer the unit test really shouldn't care about. Unless, that is, you're in fact attempting integration testing instead. That would be another situation entirely.... Hope this helps.

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