Spring Test & Security: How to mock authentication?

后端 未结 7 1541
野性不改
野性不改 2020-11-28 01:27

I was trying to figure out how to unit test if my the URLs of my controllers are properly secured. Just in case someone changes things around and accidentally removes securi

7条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-28 01:54

    Options to avoid using SecurityContextHolder in tests:

    • Option 1: use mocks - I mean mock SecurityContextHolder using some mock library - EasyMock for example
    • Option 2: wrap call SecurityContextHolder.get... in your code in some service - for example in SecurityServiceImpl with method getCurrentPrincipal that implements SecurityService interface and then in your tests you can simply create mock implementation of this interface that returns the desired principal without access to SecurityContextHolder.

提交回复
热议问题