Best Mockito code snippet using org.mockito.Mockito.withHeader
Source:StoreReaderDotNetTest.java
...82 TransportClient mockTransportClient = Mockito.mock(TransportClient.class);83 // create mock store response object84 StoreResponseBuilder srb = new StoreResponseBuilder();85 // set lsn and activityid on the store response.86 srb.withHeader(WFConstants.BackendHeaders.ACTIVITY_ID, "ACTIVITYID1_1" );87 srb.withHeader(WFConstants.BackendHeaders.LSN, "50");88 // setup mock transport client89 Mockito.doReturn(Mono.just(srb.build()))90 .when(mockTransportClient)91 .invokeResourceOperationAsync(92 Mockito.eq(addressInformation[0].getPhysicalUri()),93 Mockito.any(RxDocumentServiceRequest.class));94 // get response from mock object95 StoreResponse response = mockTransportClient.invokeResourceOperationAsync(addressInformation[0].getPhysicalUri(), entity).block();96 // validate that the LSN matches97 // validate that the ActivityId Matches98 StoreResponseValidator validator = StoreResponseValidator.create().withBELSN(50).withBEActivityId("ACTIVITYID1_1").build();99 validator.validate(response);100 }101 private TransportClient getMockTransportClientDuringUpgrade(AddressInformation[] addressInformation) {102 // create objects for all the dependencies of the StoreReader103 TransportClient mockTransportClient = Mockito.mock(TransportClient.class);104 // create mock store response object105 // set lsn and activityid on the store response.106 StoreResponse mockStoreResponseFast = StoreResponseBuilder.create()107 .withHeader(WFConstants.BackendHeaders.LSN, "50")108 .withHeader(WFConstants.BackendHeaders.ACTIVITY_ID, "ACTIVITYID1_1")109 .build();110 StoreResponse mockStoreResponseSlow = StoreResponseBuilder.create()111 .withHeader(WFConstants.BackendHeaders.LSN, "30")112 .withHeader(WFConstants.BackendHeaders.ACTIVITY_ID, "ACTIVITYID1_1")113 .build();114 // setup mock transport client for the first replica115 Mockito.doReturn(Mono.just(mockStoreResponseFast))116 .when(mockTransportClient)117 .invokeResourceOperationAsync(Mockito.eq(addressInformation[0].getPhysicalUri()), Mockito.any(RxDocumentServiceRequest.class));118 // setup mock transport client with a sequence of outputs119 Mockito.doReturn(Mono.just(mockStoreResponseFast)) // initial read response120 .doReturn(Mono.just(mockStoreResponseFast)) // barrier retry, count 1121 .doReturn(Mono.just(mockStoreResponseFast)) // barrier retry, count 2122 .doReturn(Mono.error(new InvalidPartitionException())) // throw invalid partition exception to simulate collection recreate with same name123 .doReturn(Mono.just(mockStoreResponseFast)) // new read124 .doReturn(Mono.just(mockStoreResponseFast)) // subsequent barriers125 .doReturn(Mono.just(mockStoreResponseFast))126 .doReturn(Mono.just(mockStoreResponseFast))127 .when(mockTransportClient).invokeResourceOperationAsync(128 Mockito.eq(addressInformation[1].getPhysicalUri()),129 Mockito.any(RxDocumentServiceRequest.class));130 // After this, the product code should reset target identity, and lsn response131 Queue<StoreResponse> queueOfResponses = new ArrayDeque<>();132 // let the first 10 responses be slow, and then fast133 for (int i = 0; i < 20; i++) {134 queueOfResponses.add(i <= 2 ? mockStoreResponseSlow : mockStoreResponseFast);135 }136 // setup mock transport client with a sequence of outputs, for the second replica137 // This replica behaves in the following manner:138 // calling InvokeResourceOperationAsync139 // 1st time: returns valid LSN140 // 2nd time: returns InvalidPartitionException141 // initial read response142 Mockito.doAnswer((params) -> Mono.just(queueOfResponses.poll()))143 .when(mockTransportClient).invokeResourceOperationAsync(144 Mockito.eq(addressInformation[2].getPhysicalUri()),145 Mockito.any(RxDocumentServiceRequest.class));146 return mockTransportClient;147 }148 private enum ReadQuorumResultKind {149 QuorumMet,150 QuorumSelected,151 QuorumNotSelected152 }153 private TransportClient getMockTransportClientForGlobalStrongReads(AddressInformation[] addressInformation, ReadQuorumResultKind result) {154 // create objects for all the dependencies of the StoreReader155 TransportClient mockTransportClient = Mockito.mock(TransportClient.class);156 // create mock store response object157 StoreResponse mockStoreResponse1 = StoreResponseBuilder.create()158 .withHeader(WFConstants.BackendHeaders.LSN, "100")159 .withHeader(WFConstants.BackendHeaders.GLOBAL_COMMITTED_LSN, "90")160 .withHeader(WFConstants.BackendHeaders.ACTIVITY_ID, "ACTIVITYID1_1")161 .withHeader(WFConstants.BackendHeaders.NUMBER_OF_READ_REGIONS, "1")162 .build();163 StoreResponse mockStoreResponse2 = StoreResponseBuilder.create()164 .withHeader(WFConstants.BackendHeaders.LSN, "90")165 .withHeader(WFConstants.BackendHeaders.GLOBAL_COMMITTED_LSN, "90")166 .withHeader(WFConstants.BackendHeaders.ACTIVITY_ID, "ACTIVITYID1_2")167 .withHeader(WFConstants.BackendHeaders.NUMBER_OF_READ_REGIONS, "1")168 .build();169 StoreResponse mockStoreResponse3 = StoreResponseBuilder.create()170 .withHeader(WFConstants.BackendHeaders.LSN, "92")171 .withHeader(WFConstants.BackendHeaders.GLOBAL_COMMITTED_LSN, "90")172 .withHeader(WFConstants.BackendHeaders.ACTIVITY_ID, "ACTIVITYID1_3")173 .withHeader(WFConstants.BackendHeaders.NUMBER_OF_READ_REGIONS, "1")174 .build();175 StoreResponse mockStoreResponse4 = StoreResponseBuilder.create()176 .withHeader(WFConstants.BackendHeaders.LSN, "100")177 .withHeader(WFConstants.BackendHeaders.GLOBAL_COMMITTED_LSN, "92")178 .withHeader(WFConstants.BackendHeaders.ACTIVITY_ID, "ACTIVITYID1_3")179 .withHeader(WFConstants.BackendHeaders.NUMBER_OF_READ_REGIONS, "1")180 .build();181 StoreResponse mockStoreResponse5 = StoreResponseBuilder.create()182 .withHeader(WFConstants.BackendHeaders.LSN, "100")183 .withHeader(WFConstants.BackendHeaders.GLOBAL_COMMITTED_LSN, "100")184 .withHeader(WFConstants.BackendHeaders.ACTIVITY_ID, "ACTIVITYID1_3")185 .withHeader(WFConstants.BackendHeaders.NUMBER_OF_READ_REGIONS, "1")186 .withHeader(WFConstants.BackendHeaders.CURRENT_REPLICA_SET_SIZE, "1")187 .withHeader(WFConstants.BackendHeaders.QUORUM_ACKED_LSN, "100")188 .build();189 // set lsn and activityid on the store response.190 StoreResponse mockStoreResponseFast = StoreResponseBuilder.create()191 .withHeader(WFConstants.BackendHeaders.LSN, "50")192 .withHeader(WFConstants.BackendHeaders.ACTIVITY_ID, "ACTIVITYID1_1")193 .build();194 if(result == ReadQuorumResultKind.QuorumMet) {195 // setup mock transport client for the first replica196 Mockito.doReturn(Mono.just(mockStoreResponse5))197 .when(mockTransportClient).invokeResourceOperationAsync(198 Mockito.eq(addressInformation[0].getPhysicalUri()), Mockito.any(RxDocumentServiceRequest.class));199 Mockito.doReturn(Mono.just(mockStoreResponse1))200 .doReturn(Mono.just(mockStoreResponse1))201 .doReturn(Mono.just(mockStoreResponse1))202 .doReturn(Mono.just(mockStoreResponse1))203 .doReturn(Mono.just(mockStoreResponse1))204 .doReturn(Mono.just(mockStoreResponse5))205 .when(mockTransportClient).invokeResourceOperationAsync(206 Mockito.eq(addressInformation[1].getPhysicalUri()),207 Mockito.any(RxDocumentServiceRequest.class));208 Mockito.doReturn(Mono.just(mockStoreResponse2))209 .doReturn(Mono.just(mockStoreResponse2))210 .doReturn(Mono.just(mockStoreResponse2))211 .doReturn(Mono.just(mockStoreResponse1))212 .doReturn(Mono.just(mockStoreResponse4))213 .doReturn(Mono.just(mockStoreResponse5))214 .when(mockTransportClient).invokeResourceOperationAsync(215 Mockito.eq(addressInformation[2].getPhysicalUri()),216 Mockito.any(RxDocumentServiceRequest.class));217 }218 if (result == ReadQuorumResultKind.QuorumSelected) {219 // setup mock transport client for the first replica220 Mockito.doReturn(Mono.just(mockStoreResponse2))221 .when(mockTransportClient).invokeResourceOperationAsync(222 Mockito.eq(addressInformation[0].getPhysicalUri()), Mockito.any(RxDocumentServiceRequest.class));223 // setup mock transport client with a sequence of outputs224 Mockito.doReturn(Mono.just(mockStoreResponse1))225 .when(mockTransportClient).invokeResourceOperationAsync(226 Mockito.eq(addressInformation[1].getPhysicalUri()), Mockito.any(RxDocumentServiceRequest.class));227 // setup mock transport client with a sequence of outputs228 Mockito.doReturn(Mono.just(mockStoreResponse2))229 .when(mockTransportClient).invokeResourceOperationAsync(230 Mockito.eq(addressInformation[2].getPhysicalUri()), Mockito.any(RxDocumentServiceRequest.class));231 } else if (result == ReadQuorumResultKind.QuorumNotSelected) {232 // setup mock transport client for the first replica233 Mockito.doReturn(Mono.just(mockStoreResponse5))234 .when(mockTransportClient).invokeResourceOperationAsync(235 Mockito.eq(addressInformation[0].getPhysicalUri()), Mockito.any(RxDocumentServiceRequest.class));236 Mockito.doReturn(Mono.just(mockStoreResponse5))237 .when(mockTransportClient).invokeResourceOperationAsync(238 Mockito.eq(addressInformation[1].getPhysicalUri()), Mockito.any(RxDocumentServiceRequest.class));239 Mockito.doReturn(Mono.error(new GoneException("test")))240 .when(mockTransportClient).invokeResourceOperationAsync(241 Mockito.eq(addressInformation[2].getPhysicalUri()), Mockito.any(RxDocumentServiceRequest.class));242 }243 return mockTransportClient;244 }245 private TransportClient getMockTransportClientForGlobalStrongWrites(246 AddressInformation[] addressInformation,247 int indexOfCaughtUpReplica,248 boolean undershootGlobalCommittedLsnDuringBarrier,249 boolean overshootLsnDuringBarrier,250 boolean overshootGlobalCommittedLsnDuringBarrier)251 {252 TransportClient mockTransportClient = Mockito.mock(TransportClient.class);253 // create mock store response object254 // set lsn and activityid on the store response.255 StoreResponse mockStoreResponse1 = StoreResponseBuilder.create()256 .withHeader(WFConstants.BackendHeaders.LSN, "100")257 .withHeader(WFConstants.BackendHeaders.ACTIVITY_ID, "ACTIVITYID1_1")258 .withHeader(WFConstants.BackendHeaders.GLOBAL_COMMITTED_LSN, "90")259 .withHeader(WFConstants.BackendHeaders.NUMBER_OF_READ_REGIONS, "1")260 .build();261 StoreResponse mockStoreResponse2 = StoreResponseBuilder.create()262 .withHeader(WFConstants.BackendHeaders.LSN, "100")263 .withHeader(WFConstants.BackendHeaders.ACTIVITY_ID, "ACTIVITYID1_2")264 .withHeader(WFConstants.BackendHeaders.GLOBAL_COMMITTED_LSN, "100")265 .withHeader(WFConstants.BackendHeaders.NUMBER_OF_READ_REGIONS, "1")266 .build();267 StoreResponse mockStoreResponse3 = StoreResponseBuilder.create()268 .withHeader(WFConstants.BackendHeaders.LSN, "103")269 .withHeader(WFConstants.BackendHeaders.ACTIVITY_ID, "ACTIVITYID1_3")270 .withHeader(WFConstants.BackendHeaders.GLOBAL_COMMITTED_LSN, "100")271 .withHeader(WFConstants.BackendHeaders.NUMBER_OF_READ_REGIONS, "1")272 .build();273 StoreResponse mockStoreResponse4 = StoreResponseBuilder.create()274 .withHeader(WFConstants.BackendHeaders.LSN, "103")275 .withHeader(WFConstants.BackendHeaders.ACTIVITY_ID, "ACTIVITYID1_3")276 .withHeader(WFConstants.BackendHeaders.GLOBAL_COMMITTED_LSN, "103")277 .withHeader(WFConstants.BackendHeaders.NUMBER_OF_READ_REGIONS, "1")278 .build();279 StoreResponse mockStoreResponse5 = StoreResponseBuilder.create()280 .withHeader(WFConstants.BackendHeaders.LSN, "106")281 .withHeader(WFConstants.BackendHeaders.ACTIVITY_ID, "ACTIVITYID1_3")282 .withHeader(WFConstants.BackendHeaders.GLOBAL_COMMITTED_LSN, "103")283 .withHeader(WFConstants.BackendHeaders.NUMBER_OF_READ_REGIONS, "1")284 .build();285 StoreResponse finalResponse = null;286 if (undershootGlobalCommittedLsnDuringBarrier) {287 finalResponse = mockStoreResponse1;288 } else {289 if (overshootLsnDuringBarrier) {290 if (overshootGlobalCommittedLsnDuringBarrier) {291 finalResponse = mockStoreResponse5;292 } else {293 finalResponse = mockStoreResponse3;294 }295 } else {296 if (overshootGlobalCommittedLsnDuringBarrier) {297 finalResponse = mockStoreResponse4;...
Source:JenkinsGetRootUrlTest.java
...96 accessing("http://ci:8080/jenkins/");97 rootUrlFromRequestIs("http://ci:8080/jenkins/");98 // With a forwarded protocol, it should use the forwarded protocol99 accessing("https://ci/jenkins/");100 withHeader("X-Forwarded-Proto", "https");101 rootUrlFromRequestIs("https://ci/jenkins/");102 accessing("http://ci/jenkins/");103 withHeader("X-Forwarded-Proto", "http");104 rootUrlFromRequestIs("http://ci/jenkins/");105 // ServletRequest.getServerPort is not always meaningful.106 // http://tomcat.apache.org/tomcat-5.5-doc/config/http.html#Proxy_Support or107 // http://wiki.eclipse.org/Jetty/Howto/Configure_mod_proxy#Configuring_mod_proxy_as_a_Reverse_Proxy.5D108 // can be used to ensure that it is hardcoded or that X-Forwarded-Port is interpreted.109 // But this is not something that can be configured purely from the reverse proxy; the container must be modified too.110 // And the standard bundled Jetty in Jenkins does not work that way;111 // it will return 80 even when Jenkins is fronted by Apache with SSL.112 accessing("http://ci/jenkins/"); // as if the container is not aware of the forwarded port113 withHeader("X-Forwarded-Port", "443"); // but we tell it114 withHeader("X-Forwarded-Proto", "https");115 rootUrlFromRequestIs("https://ci/jenkins/");116 }117 @Issue("JENKINS-58041")118 @Test119 public void useForwardedProtoWithIPv6WhenPresent() {120 configured("http://[::1]/jenkins/");121 // Without a forwarded protocol, it should use the request protocol122 accessing("http://[::1]/jenkins/");123 rootUrlFromRequestIs("http://[::1]/jenkins/");124 125 accessing("http://[::1]:8080/jenkins/");126 rootUrlFromRequestIs("http://[::1]:8080/jenkins/");127 // With a forwarded protocol, it should use the forwarded protocol128 accessing("http://[::1]/jenkins/");129 withHeader("X-Forwarded-Host", "[::2]");130 rootUrlFromRequestIs("http://[::2]/jenkins/");131 accessing("http://[::1]:8080/jenkins/");132 withHeader("X-Forwarded-Proto", "https");133 withHeader("X-Forwarded-Host", "[::1]:8443");134 rootUrlFromRequestIs("https://[::1]:8443/jenkins/");135 }136 private void rootUrlFromRequestIs(final String expectedRootUrl) {137 138 assertThat(jenkins.getRootUrlFromRequest(), equalTo(expectedRootUrl));139 }140 private void rootUrlIs(final String expectedRootUrl) {141 assertThat(jenkins.getRootUrl(), equalTo(expectedRootUrl));142 }143 private void configured(final String configuredHost) {144 when(config.getUrl()).thenReturn(configuredHost);145 }146 147 private void withHeader(String name, final String value) {148 final StaplerRequest req = Stapler.getCurrentRequest();149 when(req.getHeader(name)).thenReturn(value);150 }151 private void accessing(final String realUrl) {152 final URL url = getUrl(realUrl);153 final StaplerRequest req = mock(StaplerRequest.class);154 when(req.getScheme()).thenReturn(url.getProtocol());155 when(req.getServerName()).thenReturn(url.getHost());156 when(req.getServerPort()).thenReturn(url.getPort() == -1 ? ("https".equals(url.getProtocol()) ? 443 : 80) : url.getPort());157 when(req.getContextPath()).thenReturn(url.getPath().replaceAll("/$", ""));158 when(req.getIntHeader(anyString())).thenAnswer(new Answer<Integer>() {159 @Override public Integer answer(InvocationOnMock invocation) throws Throwable {160 String name = (String) invocation.getArguments()[0];161 String value = ((StaplerRequest) invocation.getMock()).getHeader(name);...
Source:HttpStubAuthenticatorTest.java
...48 public void testAllow() throws URISyntaxException, KeyManagementException, IOReactorException, NoSuchAlgorithmException, KeyStoreException {49 auth.attach(Mockito.mock(AuthConnector.class));50 final StubAuthResponse expected = new StubAuthResponse(1000L);51 stubFor(post(urlEqualTo(MOCK_PATH))52 .withHeader("Accept", equalTo("application/json"))53 .willReturn(aResponse()54 .withStatus(200)55 .withHeader("Content-Type", "application/json")56 .withBody(gson.toJson(expected))));57 final EdgeNexus nexus = new EdgeNexus(null, LocalPeer.instance());58 nexus.getSession().setCredentials(new BasicAuthCredentials("user", "pass"));59 final AuthenticationOutcome outcome = Mockito.mock(AuthenticationOutcome.class);60 auth.verify(nexus, TOPIC, outcome);61 SocketUtils.await().until(() -> {62 Mockito.verify(outcome).allow(Mockito.eq(1000L));63 });64 verify(postRequestedFor(urlMatching(MOCK_PATH)));65 }66 @Test67 public void testAllowHttps() throws URISyntaxException, KeyManagementException, IOReactorException, NoSuchAlgorithmException, KeyStoreException {68 auth.getConfig().withURI(getURI(true));69 auth.attach(Mockito.mock(AuthConnector.class));70 final StubAuthResponse expected = new StubAuthResponse(1000L);71 stubFor(post(urlEqualTo(MOCK_PATH))72 .withHeader("Accept", equalTo("application/json"))73 .willReturn(aResponse()74 .withStatus(200)75 .withHeader("Content-Type", "application/json")76 .withBody(gson.toJson(expected))));77 final EdgeNexus nexus = new EdgeNexus(null, LocalPeer.instance());78 nexus.getSession().setCredentials(new BasicAuthCredentials("user", "pass"));79 final AuthenticationOutcome outcome = Mockito.mock(AuthenticationOutcome.class);80 auth.verify(nexus, TOPIC, outcome);81 SocketUtils.await().until(() -> {82 Mockito.verify(outcome).allow(1000L);83 });84 verify(postRequestedFor(urlMatching(MOCK_PATH)));85 }86 @Test87 public void testDeny() throws URISyntaxException, KeyManagementException, IOReactorException, NoSuchAlgorithmException, KeyStoreException {88 auth.attach(Mockito.mock(AuthConnector.class));89 final StubAuthResponse expected = new StubAuthResponse(null);90 stubFor(post(urlEqualTo(MOCK_PATH))91 .withHeader("Accept", equalTo("application/json"))92 .willReturn(aResponse()93 .withStatus(200)94 .withHeader("Content-Type", "application/json")95 .withBody(gson.toJson(expected))));96 final EdgeNexus nexus = new EdgeNexus(null, LocalPeer.instance());97 nexus.getSession().setCredentials(new BasicAuthCredentials("user", "pass"));98 final AuthenticationOutcome outcome = Mockito.mock(AuthenticationOutcome.class);99 auth.verify(nexus, TOPIC, outcome);100 SocketUtils.await().until(() -> {101 Mockito.verify(outcome).forbidden(Mockito.eq(TOPIC));102 });103 verify(postRequestedFor(urlMatching(MOCK_PATH)));104 }105 @Test106 public void testBadStatusCode() throws URISyntaxException, KeyManagementException, IOReactorException, NoSuchAlgorithmException, KeyStoreException {107 auth.attach(Mockito.mock(AuthConnector.class));108 stubFor(post(urlEqualTo(MOCK_PATH))109 .withHeader("Accept", equalTo("application/json"))110 .willReturn(aResponse()111 .withStatus(404)));112 final EdgeNexus nexus = new EdgeNexus(null, LocalPeer.instance());113 nexus.getSession().setCredentials(new BasicAuthCredentials("user", "pass"));114 final AuthenticationOutcome outcome = Mockito.mock(AuthenticationOutcome.class);115 auth.verify(nexus, TOPIC, outcome);116 SocketUtils.await().until(() -> {117 Mockito.verify(outcome).forbidden(Mockito.eq(TOPIC));118 });119 verify(postRequestedFor(urlMatching(MOCK_PATH)));120 }121 @Test122 public void testBadEntity() throws URISyntaxException, KeyManagementException, IOReactorException, NoSuchAlgorithmException, KeyStoreException {123 auth.attach(Mockito.mock(AuthConnector.class));124 stubFor(post(urlEqualTo(MOCK_PATH))125 .withHeader("Accept", equalTo("application/json"))126 .willReturn(aResponse()127 .withStatus(200)128 .withHeader("Content-Type", "application/json")129 .withBody("}{")));130 final EdgeNexus nexus = new EdgeNexus(null, LocalPeer.instance());131 nexus.getSession().setCredentials(new BasicAuthCredentials("user", "pass"));132 final AuthenticationOutcome outcome = Mockito.mock(AuthenticationOutcome.class);133 auth.verify(nexus, TOPIC, outcome);134 SocketUtils.await().until(() -> {135 Mockito.verify(outcome).forbidden(Mockito.eq(TOPIC));136 });137 verify(postRequestedFor(urlMatching(MOCK_PATH)));138 }139 @Test140 public void testTimeout() throws URISyntaxException, KeyManagementException, IOReactorException, NoSuchAlgorithmException, KeyStoreException {141 auth.getConfig().withTimeoutMillis(1);142 auth.attach(Mockito.mock(AuthConnector.class));143 stubFor(post(urlEqualTo(MOCK_PATH))144 .withHeader("Accept", equalTo("application/json"))145 .willReturn(aResponse()146 .withFixedDelay(10_000)147 .withStatus(200)148 .withHeader("Content-Type", "application/json")149 .withBody("")));150 final EdgeNexus nexus = new EdgeNexus(null, LocalPeer.instance());151 nexus.getSession().setCredentials(new BasicAuthCredentials("user", "pass"));152 final AuthenticationOutcome outcome = Mockito.mock(AuthenticationOutcome.class);153 auth.verify(nexus, TOPIC, outcome);154 SocketUtils.await().until(() -> {155 Mockito.verify(outcome).forbidden(Mockito.eq(TOPIC));156 });157 }158 private URI getURI(boolean https) throws URISyntaxException {159 return new WireMockURIBuilder()160 .withWireMock(wireMock)161 .withHttps(https)162 .withPath(MOCK_PATH)...
Source:ProxyTest.java
...40 @MockBean TokenService tokenService;41 @BeforeEach42 void setUp() {43 stubFor(WireMock.post("/soap")44 .withHeader("test-header", equalTo("test-value"))45 .willReturn(aResponse()46 .withBody("TEST")47 .withHeader("test-header", "test-value")));48 stubFor(WireMock.post("/soap")49 .withHeader("Authorization", equalTo("Bearer GOOD_TOKEN"))50 .willReturn(aResponse()51 .withBody("AUTHOK")52 .withHeader("test-header", "test-value")));53 stubFor(WireMock.post("/soap")54 .withHeader("Authorization", equalTo("Bearer BAD_TOKEN"))55 .willReturn(aResponse()56 .withStatus(401)57 .withBody("1012116 - Invalid token.")58 .withHeader(HttpHeaders.WWW_AUTHENTICATE, "OAuth realm=\"AKANA OAUTH LibertyGlobal\" error=\"1012116 - Invalid token.")59 .withHeader("Strict-Transport-Security", "max-age=31536000; includeSubDomains")60 .withHeader(HttpHeaders.CONNECTION, "close")61 ));62 stubFor(WireMock.post("/soap")63 .withHeader("Authorization", equalTo("Bearer BAD_DATA"))64 .withRequestBody(equalTo("BAD_DATA"))65 .willReturn(badRequest()));66 stubFor(WireMock.post("/soap")67 .withHeader("Authorization", equalTo("Bearer SERVER_ERROR"))68 .withRequestBody(equalTo("SERVER_ERROR"))69 .willReturn(serverError()));70 reset(tokenService);71 }72 @Test73 void testEcho() throws Exception {74 mvc.perform(get("http://localhost:{port}/", port))75 .andDo(print())76 .andExpect(content().string(containsString("server.port=0")))77 .andExpect(content().string(containsString("http.client.ssl.trust-store-password=st*********rd")))78 ;79 }80 @Test81 void testEchoRoot() throws Exception {...
Source:UploaderTest.java
...138 private MappingBuilder makeCall(int code) throws Exception {139 String encodedBeaconKey = Base64.encodeToString(140 BEACON_KEY.getBytes("ASCII"), Base64.NO_WRAP);141 return WireMock.put(WireMock.urlEqualTo(requestPath))142 .withHeader("Accept", WireMock.equalTo("application/json"))143 .withHeader("Authorization", WireMock.equalTo("Basic " + encodedBeaconKey))144 .withHeader("Content-Encoding", WireMock.equalTo("gzip"))145 .withHeader("Content-Type", WireMock.equalTo("application/json"))146 .willReturn(makeResponse(code));147 }148 private ResponseDefinitionBuilder makeResponse(int code) {149 return WireMock.aResponse().withStatus(code);150 }151}...
Source:SesarClientTest.java
...42 }43 @Test44 public void testCheckAuthenticationValid() {45 stubFor(post(urlEqualTo("/credentials_service.php"))46 .withHeader("Accept", containing("text/xml"))47 .willReturn(aResponse()48 .withStatus(200)49 .withHeader("Content-Type", "text/xml")50 .withBody(""51 + "<results>\n"52 + " <valid>yes</valid>\n"53 + " <user_codes>\n"54 + " <user_code>MOB</user_code>\n"55 + " </user_codes>\n"56 + "</results> ")));57 assertThat(client.checkAuthentication()).isTrue();58 }59 @Test60 public void testCheckAuthenticationInvalid() {61 stubFor(post(urlEqualTo("/credentials_service.php"))62 .withHeader("Accept", containing("text/xml"))63 .willReturn(aResponse()64 .withStatus(401)65 .withHeader("Content-Type", "text/xml")66 .withBody(""67 + "<results>\n"68 + " <valid>no</valid>\n"69 + " <error>Invalid login, username not known or password not matched</error>\n"70 + "</results>")));71 assertThat(client.checkAuthentication()).isFalse();72 }73 @Test74 public void testRegister() throws Exception {75 Samples samples = new Samples();76 Samples.Sample samplesSample = new Samples.Sample();77 samplesSample.setUserCode("JJZ");78 samplesSample.setName("Test");79 samples.getSample().add(samplesSample);80 when(sampleMapper.translateToSesarSamples(sampleSource)).thenReturn(samples);81 stubFor(post(urlEqualTo("/upload.php"))82 .withHeader("Accept", containing("text/xml"))83 .willReturn(aResponse()84 .withStatus(200)85 .withHeader("Content-Type", "text/xml")86 .withBody("<response>Some content</response>")));87 client.register(sampleSource);88 verify(postRequestedFor(urlMatching("/upload.php"))89 .withRequestBody(containing("username=username"))90 .withRequestBody(containing("password=password"))91 .withRequestBody(containing("content=%3C%3Fxml+version%3D%221.0%22"))92 .withRequestBody(containing("%3Cname%3ETest%3C%2Fname%3E"))93 .withRequestBody(containing("%3Cuser_code%3EJJZ%3C%2Fuser_code%3E")));94 }95}...
Source:AllocateProfileTest.java
...32//33// @Test34// public void shouldReturnAcToken() {35// wireMockRule.stubFor(post(urlMatching("/custom/profile/"))36// .withHeader("Content-type", equalTo("application/x-www-form-urlencoded"))37// .withHeader("User-Agent", equalTo("gsma-rsp-com.truphone.lpad"))38// .withHeader("X-Admin-Protocol", equalTo("gsma/rsp/v2.2.0"))39// .withRequestBody(containing("eid=89044050001000680000000000000170&mcc=351"))40// .willReturn(aResponse().withStatus(200).withBody("$1$rsp.truphone.com$2")));41//42// when(mockApduChannel.transmitAPDU(anyString()))43// .thenReturn(ReferenceData.VALID_EID);44//45// Assert.assertEquals("2", localProfileAssistant.allocateProfile("351"));46// }47//48// @Test(expected = RuntimeException.class)49// public void shouldThrowRuntimeExceptionWhenRspServerRespondesWithEmpty() {50// wireMockRule.stubFor(post(urlMatching("/custom/profile/"))51// .withHeader("Content-type", equalTo("application/x-www-form-urlencoded"))52// .withHeader("User-Agent", equalTo("gsma-rsp-com.truphone.lpad"))53// .withHeader("X-Admin-Protocol", equalTo("gsma/rsp/v2.2.0"))54// .withRequestBody(containing("eid=89044050001000680000000000000170&mcc=351"))55// .willReturn(aResponse().withStatus(200).withBody("x")));56//57// when(mockApduChannel.transmitAPDU(anyString()))58// .thenReturn(ReferenceData.VALID_EID);59//60// localProfileAssistant.allocateProfile("351");61// }62//63//64// @Test(expected = RuntimeException.class)65// public void shouldThrowRuntimeExceptionWhenRspServerRespondesWithStatusDifferentOf2xx() {66// wireMockRule.stubFor(post(urlMatching("/custom/profile/"))67// .withHeader("Content-type", equalTo("application/x-www-form-urlencoded"))68// .withHeader("User-Agent", equalTo("gsma-rsp-com.truphone.lpad"))69// .withHeader("X-Admin-Protocol", equalTo("gsma/rsp/v2.2.0"))70// .withRequestBody(containing("eid=89044050001000680000000000000170&mcc=351"))71// .willReturn(aResponse().withStatus(400).withBody("x")));72//73// when(mockApduChannel.transmitAPDU(anyString()))74// .thenReturn(ReferenceData.VALID_EID);75//76// localProfileAssistant.allocateProfile("351");77// }78}...
Source:OAuth2TokenStrategyTest.java
...32 }33 @Test34 public void applies() throws Exception {35 oAuth2TokenStrategy.apply(request, auth);36 verify(request).withHeader("Authorization", "token value");37 }38 @Test39 public void verifyGetType() throws Exception {40 assertThat(oAuth2TokenStrategy.getType()).isEqualTo("forward-oauth2-token");41 }42 @Test43 public void appliesWithNullTokenType() throws Exception {44 when(details.getTokenType()).thenReturn(null);45 oAuth2TokenStrategy.apply(request, auth);46 verify(request).withHeader("Authorization", "Bearer value");47 }48 @Test49 public void doesntApplyWithNullHeader() throws Exception {50 oAuth2TokenStrategy.apply(request, null);51 verify(request, times(0)).withHeader("Authorization", "token value");52 }53 @Test54 public void doesntApplyWithWrongDetails() throws Exception {55 when(auth.getDetails()).thenReturn("wrong details type");56 oAuth2TokenStrategy.apply(request, auth);57 verify(request, times(0)).withHeader("Authorization", "token value");58 }59}
withHeader
Using AI Code Generation
1import org.mockito.Mockito;2import org.mockito.invocation.InvocationOnMock;3import org.mockito.stubbing.Answer;4import org.springframework.http.HttpHeaders;5import org.springframework.http.HttpStatus;6import org.springframework.http.ResponseEntity;7public class MockitoWithHeaderExample {8 public static void main(String[] args) {9 ResponseEntity<String> responseEntity = Mockito.mock(ResponseEntity.class);10 Mockito.when(responseEntity.getHeaders()).thenAnswer(new Answer<HttpHeaders>() {11 public HttpHeaders answer(InvocationOnMock invocation) throws Throwable {12 return new HttpHeaders();13 }14 });15 responseEntity.getHeaders().add("key", "value");16 System.out.println(responseEntity.getHeaders());17 }18}19{key=[value]}
withHeader
Using AI Code Generation
1package com.automationrhapsody.mockito;2import static org.mockito.Mockito.when;3import java.util.ArrayList;4import java.util.List;5import org.junit.Test;6import org.junit.runner.RunWith;7import org.mockito.InjectMocks;8import org.mockito.Mock;9import org.mockito.runners.MockitoJUnitRunner;10@RunWith(MockitoJUnitRunner.class)11public class MockitoWithHeaderTest {12 private Header header;13 private Header header2;14 private HeaderService headerService;15 public void testWithHeader() {16 when(headerService.getHeaders()).thenReturn(header);17 when(headerService.getHeaders2()).thenReturn(header2);18 }19}20package com.automationrhapsody.mockito;21import static org.mockito.Mockito.mock;22import static org.mockito.Mockito.when;23import org.junit.Test;24import org.junit.runner.RunWith;25import org.mockito.Mock;26import org.mockito.runners.MockitoJUnitRunner;27@RunWith(MockitoJUnitRunner.class)28public class MockitoWithHeaderTest {29 private Header header;30 private Header header2;31 public void testWithHeader() {32 HeaderService headerService = mock(HeaderService.class);33 when(headerService.getHeaders()).thenReturn(header);34 when(headerService.getHeaders2()).thenReturn(header2);35 }36}37package com.automationrhapsody.mockito;38import static org.mockito.Mockito.mock;39import static org.mockito.Mockito.when;40import org.junit.Test;41public class MockitoWithHeaderTest {42 public void testWithHeader() {43 HeaderService headerService = mock(HeaderService.class);44 Header header = mock(Header.class);45 Header header2 = mock(Header.class);46 when(headerService.getHeaders()).thenReturn(header);47 when(headerService.getHeaders2()).thenReturn(header2);48 }49}50package com.automationrhapsody.mockito;51import static org.mockito.Mockito.mock;52import static org.mockito.Mockito.when;53import org.junit.Test;54public class MockitoWithHeaderTest {55 public void testWithHeader() {56 HeaderService headerService = mock(HeaderService.class);
withHeader
Using AI Code Generation
1import static org.mockito.Mockito.*;2import java.util.List;3public class Example {4 public static void main(String[] args) {5 List mockedList = mock(List.class);6 when(mockedList.get(0)).thenReturn("first");7 when(mockedList.get(1)).thenThrow(new RuntimeException());8 System.out.println(mockedList.get(0));9 System.out.println(mockedList.get(1));10 System.out.println(mockedList.get(999));11 }12}13 at org.mockito.internal.stubbing.answers.ThrowsException.answer(ThrowsException.java:18)14 at org.mockito.internal.handler.MockHandlerImpl.handle(MockHandlerImpl.java:93)15 at org.mockito.internal.handler.NullResultGuardian.handle(NullResultGuardian.java:29)16 at org.mockito.internal.handler.InvocationNotifierHandler.handle(InvocationNotifierHandler.java:38)17 at org.mockito.internal.creation.bytebuddy.MockMethodInterceptor.doIntercept(MockMethodInterceptor.java:63)18 at org.mockito.internal.creation.bytebuddy.MockMethodInterceptor.doIntercept(MockMethodInterceptor.java:48)19 at org.mockito.internal.creation.bytebuddy.MockMethodInterceptor$DispatcherDefaultingToRealMethod.interceptSuperCallable(MockMethodInterceptor.java:110)20 at org.mockito.internal.creation.bytebuddy.MockMethodInterceptor$DispatcherDefaultingToRealMethod.interceptSuperCallable(MockMethodInterceptor.java:102)21 at org.mockito.internal.creation.bytebuddy.MockMethodInterceptor$DispatcherDefaultingToRealMethod.intercept(MockMethodInterceptor.java:93)22 at org.mockito.internal.creation.bytebuddy.MockMethodInterceptor.intercept(MockMethodInterceptor.java:30)23 at java.base/java.util.List.get(List.java:114)24 at Example.main(Example.java:9)
withHeader
Using AI Code Generation
1public class 1 {2 public static void main(String[] args) {3 HttpServletRequest request = mock(HttpServletRequest.class);4 when(request.getHeader("User-Agent")).thenReturn("Mozilla/5.0 (Windows NT 6.1; WOW64; rv:30.0) Gecko/20100101 Firefox/30.0");5 System.out.println(request.getHeader("User-Agent"));6 }7}8Mozilla/5.0 (Windows NT 6.1; WOW64; rv:30.0) Gecko/20100101 Firefox/30.0
withHeader
Using AI Code Generation
1public class HeaderMockitoTest {2 public void test() {3 HttpServletRequest request = mock(HttpServletRequest.class);4 when(request.getHeader("Accept")).thenReturn("application/json");5 assertEquals("application/json", request.getHeader("Accept"));6 }7}8public class HeaderMockitoTest {9 public void test() {10 HttpServletRequest request = mock(HttpServletRequest.class);11 when(request.getHeader("Accept")).thenReturn("application/json");12 assertEquals("application/json", request.getHeader("Accept"));13 }14}15public class HeaderMockitoTest {16 public void test() {17 HttpServletRequest request = mock(HttpServletRequest.class);18 when(request.getHeader("Accept")).thenReturn("application/json");19 assertEquals("application/json", request.getHeader("Accept"));20 }21}22public class HeaderMockitoTest {23 public void test() {24 HttpServletRequest request = mock(HttpServletRequest.class);25 when(request.getHeader("Accept")).thenReturn("application/json");26 assertEquals("application/json", request.getHeader("Accept"));27 }28}29public class HeaderMockitoTest {30 public void test() {31 HttpServletRequest request = mock(HttpServletRequest.class);32 when(request.getHeader("Accept")).thenReturn("application/json");33 assertEquals("application/json", request.getHeader("Accept"));34 }35}36public class HeaderMockitoTest {37 public void test() {38 HttpServletRequest request = mock(HttpServletRequest.class);39 when(request.getHeader("Accept")).thenReturn("application/json");40 assertEquals("application/json", request.getHeader("Accept"));41 }42}43public class HeaderMockitoTest {44 public void test() {45 HttpServletRequest request = mock(HttpServletRequest.class);46 when(request.getHeader("Accept")).thenReturn("application/json");47 assertEquals("application/json", request.getHeader("Accept"));48 }49}
withHeader
Using AI Code Generation
1import org.mockito.Mockito;2import org.mockito.stubbing.Stubber;3import org.mockito.stubbing.Answer;4public class MockitoWithHeader {5 public static void main(String[] args) {6 Stubber stubber = Mockito.when("test");7 Stubber stubber1 = stubber.withHeader("header", "value");8 Answer answer = Mockito.RETURNS_SMART_NULLS;9 Stubber stubber2 = stubber1.thenAnswer(answer);10 }11}12Stubber stubber = Mockito.when("test");13Stubber stubber1 = stubber.withHeader("header", "value");14Answer answer = Mockito.RETURNS_SMART_NULLS;15Stubber stubber2 = stubber1.thenAnswer(answer);
withHeader
Using AI Code Generation
1public class MockitoExample {2 public static void main(String[] args) {3 List mockedList = mock(List.class);4 when(mockedList.get(0)).withHeader("Hello");5 System.out.println(mockedList.get(0));6 }7}8public class MockitoExample {9 public static void main(String[] args) {10 List mockedList = mock(List.class);11 when(mockedList.get(0)).withHeader("Hello").thenReturn("Hi");12 System.out.println(mockedList.get(0));13 }14}15public class MockitoExample {16 public static void main(String[] args) {17 List mockedList = mock(List.class);18 when(mockedList.get(0)).withHeader("Hello").thenReturn("Hi");19 System.out.println(mockedList.get(0));20 }21}22public class MockitoExample {23 public static void main(String[] args) {24 List mockedList = mock(List.class);25 when(mockedList.get(0)).withHeader("Hello").thenReturn("Hi");26 System.out.println(mockedList.get(0));27 }28}29public class MockitoExample {30 public static void main(String[] args) {31 List mockedList = mock(List.class
withHeader
Using AI Code Generation
1package org.mockitotest;2import static org.mockito.Mockito.mock;3import static org.mockito.Mockito.when;4import javax.servlet.http.HttpServletResponse;5import org.junit.Assert;6import org.junit.Test;7public class MockTest {8public void testMockResponse() throws Exception {9HttpServletResponse mockResponse = mock(HttpServletResponse.class);10when(mockResponse.getContentType()).thenReturn("text/html");11when(mockResponse.getHeader("Content-Type")).thenReturn("text/html");12when(mockResponse.getCharacterEncoding()).thenReturn("UTF-8");13when(mockResponse.getHeader("Content-Encoding")).thenReturn("UTF-8");14when(mockResponse.getHeader("Content-Length")).thenReturn("100");15when(mockResponse.getHeader("Cache-Control")).thenReturn("no-cache");16when(mockResponse.getHeader("Pragma")).thenReturn("no-cache");17when(mockResponse.getHeader("Expires")).thenReturn("0");18when(mockResponse.getHeader("Date")).thenReturn("Thu, 01 Jan 1970 00:00:00 GMT");19Assert.assertEquals("text/html", mockResponse.getContentType());20Assert.assertEquals("text/html", mockResponse.getHeader("Content-Type"));21Assert.assertEquals("UTF-8", mockResponse.getCharacterEncoding());22Assert.assertEquals("UTF-8", mockResponse.getHeader("Content-Encoding"));23Assert.assertEquals("100", mockResponse.getHeader("Content-Length"));24Assert.assertEquals("no-cache", mockResponse.getHeader("Cache-Control"));25Assert.assertEquals("no-cache", mockResponse.getHeader("Pragma"));26Assert.assertEquals("0", mockResponse.getHeader("Expires"));27Assert.assertEquals("Thu, 01 Jan 1970 00:00:00 GMT", mockResponse.getHeader("Date"));28}29}30package org.mockitotest;31import static org.mockito.Mockito.mock;32import static org.mockito.Mockito.when;33import javax.servlet.http.HttpServletResponse;34import org.junit.Assert;35import org.junit.Test;36public class MockTest {37public void testMockResponse() throws Exception {38HttpServletResponse mockResponse = mock(HttpServletResponse.class);39when(mockResponse.getContentType()).thenReturn("text/html");40when(mockResponse.getHeader("Content-Type")).thenReturn("text/html");41when(mockResponse.getCharacterEncoding()).thenReturn("UTF-8");42when(mockResponse.getHeader("Content-Encoding")).thenReturn("UTF-8
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!