日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

在Jersey测试中模拟SecurityContext

發布時間:2023/12/3 编程问答 34 豆豆
生活随笔 收集整理的這篇文章主要介紹了 在Jersey测试中模拟SecurityContext 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

澤西極有可能編寫與澤西一起編寫的REST-API集成測試。 只需擴展類JerseyTest并繼續就可以了。

我遇到一個問題,我不得不模擬SecurityContext ,以便SecurityContext包含一個特殊的UserPrincipal 。 挑戰在于Jersey在測試中將SecurityContext包裝在自己的類SecurityContextInjectee中。 因此,我必須將SecurityContext Mock添加到此Jersey的包裝器類中。 讓我在一個示例中進行演示。

假設我有以下澤西島資源:

@Path("hello/world") public class MyJerseyResource {@GETpublic Response helloWorld(@Context final SecurityContext context) {String name = context.getUserPrincipal().getName();return Response.ok("Hello " + name, MediaType.TEXT_PLAIN).build();}}

在我的測試中,我必須模擬SecurityContext ,以便可以在測試期間使用預定義的用戶主體。 我使用Mockito作為模擬框架。 我的模擬如下

final SecurityContext securityContextMock = mock(SecurityContext.class);when(securityContextMock.getUserPrincipal()).thenReturn(new Principal() {@Overridepublic String getName() {return "Alice";}});

為了將此模擬的SecurityContext添加到包裝類SecurityContextInjectee中 ,我必須在Jersey測試中配置帶有修改后的ContainerRequestContext的ResourceConfig 。 可以在此修改后的ContainerRequestContext中設置模擬的SecurityContext ,然后在包裝器類中使用它:

@Overridepublic Application configure() {final SecurityContext securityContextMock = mock(SecurityContext.class);when(securityContextMock.getUserPrincipal()).thenReturn(new Principal() {@Overridepublic String getName() {return "Alice";}});ResourceConfig config = new ResourceConfig();config.register(new ContainerRequestFilter(){@Overridepublic void filter(final ContainerRequestContext containerRequestContext) throws IOException {containerRequestContext.setSecurityContext(securityContextMock);}});return config;}

然后,對我的資源進行的整個測試如下所示:

public class MyJerseyResourceTest extends JerseyTest {@Testpublic void helloWorld() throws Exception {Response response = target("hello/world").request().get();assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_OK);assertThat(response.getEntity()),isEqualTo("Hello Alice");}@Overridepublic Application configure() {final SecurityContext securityContextMock = mock(SecurityContext.class);when(securityContextMock.getUserPrincipal()).thenReturn(new Principal() {@Overridepublic String getName() {return "Alice";}});ResourceConfig config = new ResourceConfig();config.register(new ContainerRequestFilter(){@Overridepublic void filter(final ContainerRequestContext containerRequestContext) throws IOException {containerRequestContext.setSecurityContext(securityContextMock);}});return config;}

您是否有針對此問題的更明智的解決方案? 讓我知道,并在下面寫評論。

翻譯自: https://www.javacodegeeks.com/2018/03/mocking-securitycontext-in-jersey-tests.html

總結

以上是生活随笔為你收集整理的在Jersey测试中模拟SecurityContext的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。