How to use answer method of org.mockito.Mockito class

Best Mockito code snippet using org.mockito.Mockito.answer

Source:TestDefaultNHttpClientConnection.java Github

copy

Full Screen

...114 super();115 this.request = request;116 }117 @Override118 public Void answer(final InvocationOnMock invocation) throws Throwable {119 final Object[] args = invocation.getArguments();120 final NHttpClientConnection conn = (NHttpClientConnection) args[0];121 conn.submitRequest(request);122 return null;123 }124 }125 static class ProduceContentAnswer implements Answer<Void> {126 private final HttpAsyncContentProducer contentProducer;127 ProduceContentAnswer(final HttpAsyncContentProducer contentProducer) {128 super();129 this.contentProducer = contentProducer;130 }131 @Override132 public Void answer(final InvocationOnMock invocation) throws Throwable {133 final Object[] args = invocation.getArguments();134 final IOControl ioctrl = (IOControl) args[0];135 final ContentEncoder encoder = (ContentEncoder) args[1];136 contentProducer.produceContent(encoder, ioctrl);137 return null;138 }139 }140 @Test141 public void testProduceOutputShortMessageAfterSubmit() throws Exception {142 final BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/");143 final NStringEntity entity = new NStringEntity("stuff");144 request.setEntity(entity);145 final WritableByteChannelMock wchannel = Mockito.spy(new WritableByteChannelMock(64));146 final ByteChannelMock channel = new ByteChannelMock(null, wchannel);147 Mockito.when(session.channel()).thenReturn(channel);148 conn.submitRequest(request);149 Assert.assertEquals(19, conn.outbuf.length());150 Mockito.doAnswer(new ProduceContentAnswer(entity)).when(151 handler).outputReady(Mockito.<NHttpClientConnection>any(), Mockito.<ContentEncoder>any());152 conn.produceOutput(handler);153 Assert.assertNull(conn.getHttpRequest());154 Assert.assertNull(conn.contentEncoder);155 Assert.assertEquals("POST / HTTP/1.1\r\n\r\nstuff", wchannel.dump(Consts.ASCII));156 Mockito.verify(session, Mockito.times(1)).clearEvent(SelectionKey.OP_WRITE);157 Mockito.verify(wchannel, Mockito.times(1)).write(Matchers.<ByteBuffer>any());158 }159 @Test160 public void testProduceOutputLongMessageAfterSubmit() throws Exception {161 final BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/");162 final NStringEntity entity = new NStringEntity("a lot of various stuff");163 request.setEntity(entity);164 final WritableByteChannelMock wchannel = Mockito.spy(new WritableByteChannelMock(64));165 final ByteChannelMock channel = new ByteChannelMock(null, wchannel);166 Mockito.when(session.channel()).thenReturn(channel);167 conn.submitRequest(request);168 Assert.assertEquals(19, conn.outbuf.length());169 Mockito.doAnswer(new ProduceContentAnswer(entity)).when(170 handler).outputReady(Mockito.<NHttpClientConnection>any(), Mockito.<ContentEncoder>any());171 conn.produceOutput(handler);172 Assert.assertNull(conn.getHttpRequest());173 Assert.assertNull(conn.contentEncoder);174 Assert.assertEquals("POST / HTTP/1.1\r\n\r\na lot of various stuff", wchannel.dump(Consts.ASCII));175 Mockito.verify(session, Mockito.times(1)).clearEvent(SelectionKey.OP_WRITE);176 Mockito.verify(wchannel, Mockito.times(2)).write(Matchers.<ByteBuffer>any());177 }178 @Test179 public void testProduceOutputShortMessage() throws Exception {180 final BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/");181 final NStringEntity entity = new NStringEntity("stuff");182 request.setEntity(entity);183 final WritableByteChannelMock wchannel = Mockito.spy(new WritableByteChannelMock(64));184 final ByteChannelMock channel = new ByteChannelMock(null, wchannel);185 Mockito.when(session.channel()).thenReturn(channel);186 Mockito.doAnswer(new RequestReadyAnswer(request)).when(187 handler).requestReady(Mockito.<NHttpClientConnection>any());188 Mockito.doAnswer(new ProduceContentAnswer(entity)).when(189 handler).outputReady(Mockito.<NHttpClientConnection>any(), Mockito.<ContentEncoder>any());190 conn.produceOutput(handler);191 Assert.assertNull(conn.getHttpRequest());192 Assert.assertNull(conn.contentEncoder);193 Assert.assertEquals("POST / HTTP/1.1\r\n\r\nstuff", wchannel.dump(Consts.ASCII));194 Mockito.verify(session, Mockito.times(1)).clearEvent(SelectionKey.OP_WRITE);195 Mockito.verify(wchannel, Mockito.times(1)).write(Matchers.<ByteBuffer>any());196 }197 @Test198 public void testProduceOutputLongMessage() throws Exception {199 final BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/");200 final NStringEntity entity = new NStringEntity("a lot of various stuff");201 request.setEntity(entity);202 final WritableByteChannelMock wchannel = Mockito.spy(new WritableByteChannelMock(64));203 final ByteChannelMock channel = new ByteChannelMock(null, wchannel);204 Mockito.when(session.channel()).thenReturn(channel);205 Mockito.doAnswer(new RequestReadyAnswer(request)).when(206 handler).requestReady(Mockito.<NHttpClientConnection>any());207 Mockito.doAnswer(new ProduceContentAnswer(entity)).when(208 handler).outputReady(Mockito.<NHttpClientConnection>any(), Mockito.<ContentEncoder>any());209 conn.produceOutput(handler);210 Assert.assertNull(conn.getHttpRequest());211 Assert.assertNull(conn.contentEncoder);212 Assert.assertEquals("POST / HTTP/1.1\r\n\r\na lot of various stuff", wchannel.dump(Consts.ASCII));213 Mockito.verify(session, Mockito.times(1)).clearEvent(SelectionKey.OP_WRITE);214 Mockito.verify(wchannel, Mockito.times(2)).write(Matchers.<ByteBuffer>any());215 }216 @Test217 public void testProduceOutputLongMessageSaturatedChannel() throws Exception {218 final BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/");219 final NStringEntity entity = new NStringEntity("a lot of various stuff");220 request.setEntity(entity);221 final WritableByteChannelMock wchannel = Mockito.spy(new WritableByteChannelMock(64, 24));222 final ByteChannelMock channel = new ByteChannelMock(null, wchannel);223 Mockito.when(session.channel()).thenReturn(channel);224 Mockito.doAnswer(new RequestReadyAnswer(request)).when(225 handler).requestReady(Mockito.<NHttpClientConnection>any());226 Mockito.doAnswer(new ProduceContentAnswer(entity)).when(227 handler).outputReady(Mockito.<NHttpClientConnection>any(), Mockito.<ContentEncoder>any());228 conn.produceOutput(handler);229 Assert.assertNull(conn.getHttpRequest());230 Assert.assertNull(conn.contentEncoder);231 Assert.assertEquals("POST / HTTP/1.1\r\n\r\na lot", wchannel.dump(Consts.ASCII));232 Assert.assertEquals(17, conn.outbuf.length());233 Mockito.verify(session, Mockito.never()).clearEvent(SelectionKey.OP_WRITE);234 Mockito.verify(wchannel, Mockito.times(2)).write(Matchers.<ByteBuffer>any());235 }236 @Test237 public void testProduceOutputLongMessageSaturatedChannel2() throws Exception {238 conn = new DefaultNHttpClientConnection(session, 24);239 final BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/");240 final NStringEntity entity = new NStringEntity("a loooooooooooooooooooooooot of various stuff");241 request.setEntity(entity);242 final WritableByteChannelMock wchannel = Mockito.spy(new WritableByteChannelMock(64, 24));243 final ByteChannelMock channel = new ByteChannelMock(null, wchannel);244 Mockito.when(session.channel()).thenReturn(channel);245 Mockito.doAnswer(new RequestReadyAnswer(request)).when(246 handler).requestReady(Mockito.<NHttpClientConnection>any());247 Mockito.doAnswer(new ProduceContentAnswer(entity)).when(248 handler).outputReady(Mockito.<NHttpClientConnection>any(), Mockito.<ContentEncoder>any());249 conn.produceOutput(handler);250 Assert.assertNotNull(conn.getHttpRequest());251 Assert.assertNotNull(conn.contentEncoder);252 Assert.assertEquals("POST / HTTP/1.1\r\n\r\na loo", wchannel.dump(Consts.ASCII));253 Mockito.verify(session, Mockito.never()).clearEvent(SelectionKey.OP_WRITE);254 Mockito.verify(wchannel, Mockito.times(3)).write(Matchers.<ByteBuffer>any());255 }256 @Test257 public void testProduceOutputLongChunkedMessage() throws Exception {258 conn = new DefaultNHttpClientConnection(session, 64);259 final BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/");260 request.addHeader(HTTP.TRANSFER_ENCODING, HTTP.CHUNK_CODING);261 final NStringEntity entity = new NStringEntity("a lot of various stuff");262 entity.setChunked(true);263 request.setEntity(entity);264 final WritableByteChannelMock wchannel = Mockito.spy(new WritableByteChannelMock(64));265 final ByteChannelMock channel = new ByteChannelMock(null, wchannel);266 Mockito.when(session.channel()).thenReturn(channel);267 Mockito.doAnswer(new RequestReadyAnswer(request)).when(268 handler).requestReady(Mockito.<NHttpClientConnection>any());269 Mockito.doAnswer(new ProduceContentAnswer(entity)).when(270 handler).outputReady(Mockito.<NHttpClientConnection>any(), Mockito.<ContentEncoder>any());271 conn.produceOutput(handler);272 Assert.assertNull(conn.getHttpRequest());273 Assert.assertNull(conn.contentEncoder);274 Assert.assertEquals("POST / HTTP/1.1\r\nTransfer-Encoding: chunked\r\n\r\n" +275 "5\r\na lot\r\n11\r\n of various stuff\r\n0\r\n\r\n", wchannel.dump(Consts.ASCII));276 Mockito.verify(session, Mockito.times(1)).clearEvent(SelectionKey.OP_WRITE);277 Mockito.verify(wchannel, Mockito.times(2)).write(Matchers.<ByteBuffer>any());278 }279 @Test280 public void testProduceOutputLongChunkedMessageSaturatedChannel() throws Exception {281 conn = new DefaultNHttpClientConnection(session, 64);282 final BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/");283 request.addHeader(HTTP.TRANSFER_ENCODING, HTTP.CHUNK_CODING);284 final NStringEntity entity = new NStringEntity("a lot of various stuff");285 entity.setChunked(true);286 request.setEntity(entity);287 final WritableByteChannelMock wchannel = Mockito.spy(new WritableByteChannelMock(64, 64));288 final ByteChannelMock channel = new ByteChannelMock(null, wchannel);289 Mockito.when(session.channel()).thenReturn(channel);290 Mockito.doAnswer(new RequestReadyAnswer(request)).when(291 handler).requestReady(Mockito.<NHttpClientConnection>any());292 Mockito.doAnswer(new ProduceContentAnswer(entity)).when(293 handler).outputReady(Mockito.<NHttpClientConnection>any(), Mockito.<ContentEncoder>any());294 conn.produceOutput(handler);295 Assert.assertNull(conn.getHttpRequest());296 Assert.assertNull(conn.contentEncoder);297 Assert.assertEquals("POST / HTTP/1.1\r\nTransfer-Encoding: chunked\r\n\r\n" +298 "5\r\na lot\r\n11\r\n of", wchannel.dump(Consts.ASCII));299 Assert.assertEquals(21, conn.outbuf.length());300 Mockito.verify(session, Mockito.never()).clearEvent(SelectionKey.OP_WRITE);301 Mockito.verify(wchannel, Mockito.times(2)).write(Matchers.<ByteBuffer>any());302 }303 @Test304 public void testProduceOutputClosingConnection() throws Exception {305 final BasicHttpRequest request = new BasicHttpRequest("GET", "/");306 final WritableByteChannelMock wchannel = Mockito.spy(new WritableByteChannelMock(64));307 final ByteChannelMock channel = new ByteChannelMock(null, wchannel);308 Mockito.when(session.channel()).thenReturn(channel);309 conn.submitRequest(request);310 conn.close();311 Assert.assertEquals(NHttpConnection.CLOSING, conn.getStatus());312 conn.produceOutput(handler);313 Assert.assertEquals(NHttpConnection.CLOSED, conn.getStatus());314 Mockito.verify(wchannel, Mockito.times(1)).write(Matchers.<ByteBuffer>any());315 Mockito.verify(session, Mockito.times(1)).close();316 Mockito.verify(session, Mockito.never()).clearEvent(SelectionKey.OP_WRITE);317 Mockito.verify(handler, Mockito.never()).requestReady(318 Mockito.<NHttpClientConnection>any());319 Mockito.verify(handler, Mockito.never()).outputReady(320 Mockito.<NHttpClientConnection>any(), Mockito.<ContentEncoder>any());321 }322 static class ResponseCapturingAnswer implements Answer<Void> {323 private final LinkedList<HttpResponse> responses;324 ResponseCapturingAnswer(final LinkedList<HttpResponse> responses) {325 super();326 this.responses = responses;327 }328 @Override329 public Void answer(final InvocationOnMock invocation) throws Throwable {330 final Object[] args = invocation.getArguments();331 final NHttpClientConnection conn = (NHttpClientConnection) args[0];332 if (conn != null) {333 final HttpResponse response = conn.getHttpResponse();334 if (response != null) {335 responses.add(response);336 }337 }338 return null;339 }340 }341 static class ConsumeContentAnswer implements Answer<Void> {342 private final SimpleInputBuffer buf;343 ConsumeContentAnswer(final SimpleInputBuffer buf) {344 super();345 this.buf = buf;346 }347 @Override348 public Void answer(final InvocationOnMock invocation) throws Throwable {349 final Object[] args = invocation.getArguments();350 final ContentDecoder decoder = (ContentDecoder) args[1];351 buf.consumeContent(decoder);352 return null;353 }354 }355 @Test356 public void testConsumeInputShortMessage() throws Exception {357 final ReadableByteChannelMock rchannel = Mockito.spy(new ReadableByteChannelMock(358 new String[] {"HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nstuff"}, Consts.ASCII));359 final ByteChannelMock channel = new ByteChannelMock(rchannel, null);360 Mockito.when(session.channel()).thenReturn(channel);361 Mockito.when(session.getEventMask()).thenReturn(SelectionKey.OP_READ);362 final LinkedList<HttpResponse> responses = new LinkedList<HttpResponse>();...

Full Screen

Full Screen

Source:TestDefaultNHttpServerConnection.java Github

copy

Full Screen

...114 super();115 this.response = response;116 }117 @Override118 public Void answer(final InvocationOnMock invocation) throws Throwable {119 final Object[] args = invocation.getArguments();120 final NHttpServerConnection conn = (NHttpServerConnection) args[0];121 conn.submitResponse(response);122 return null;123 }124 }125 static class ProduceContentAnswer implements Answer<Void> {126 private final HttpAsyncContentProducer contentProducer;127 ProduceContentAnswer(final HttpAsyncContentProducer contentProducer) {128 super();129 this.contentProducer = contentProducer;130 }131 @Override132 public Void answer(final InvocationOnMock invocation) throws Throwable {133 final Object[] args = invocation.getArguments();134 final IOControl ioctrl = (IOControl) args[0];135 final ContentEncoder encoder = (ContentEncoder) args[1];136 contentProducer.produceContent(encoder, ioctrl);137 return null;138 }139 }140 @Test141 public void testProduceOutputShortMessageAfterSubmit() throws Exception {142 final BasicHttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK");143 final NStringEntity entity = new NStringEntity("stuff");144 response.setEntity(entity);145 final WritableByteChannelMock wchannel = Mockito.spy(new WritableByteChannelMock(64));146 final ByteChannelMock channel = new ByteChannelMock(null, wchannel);147 Mockito.when(session.channel()).thenReturn(channel);148 conn.submitResponse(response);149 Assert.assertEquals(19, conn.outbuf.length());150 Mockito.doAnswer(new ProduceContentAnswer(entity)).when(151 handler).outputReady(Mockito.<NHttpServerConnection>any(), Mockito.<ContentEncoder>any());152 conn.produceOutput(handler);153 Assert.assertNull(conn.getHttpResponse());154 Assert.assertNull(conn.contentEncoder);155 Assert.assertEquals("HTTP/1.1 200 OK\r\n\r\nstuff", wchannel.dump(Consts.ASCII));156 Mockito.verify(wchannel, Mockito.times(1)).write(Matchers.<ByteBuffer>any());157 }158 @Test159 public void testProduceOutputLongMessageAfterSubmit() throws Exception {160 final BasicHttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK");161 final NStringEntity entity = new NStringEntity("a lot of various stuff");162 response.setEntity(entity);163 final WritableByteChannelMock wchannel = Mockito.spy(new WritableByteChannelMock(64));164 final ByteChannelMock channel = new ByteChannelMock(null, wchannel);165 Mockito.when(session.channel()).thenReturn(channel);166 conn.submitResponse(response);167 Assert.assertEquals(19, conn.outbuf.length());168 Mockito.doAnswer(new ProduceContentAnswer(entity)).when(169 handler).outputReady(Mockito.<NHttpServerConnection>any(), Mockito.<ContentEncoder>any());170 conn.produceOutput(handler);171 Assert.assertNull(conn.getHttpResponse());172 Assert.assertNull(conn.contentEncoder);173 Assert.assertEquals("HTTP/1.1 200 OK\r\n\r\na lot of various stuff", wchannel.dump(Consts.ASCII));174 Mockito.verify(wchannel, Mockito.times(2)).write(Matchers.<ByteBuffer>any());175 }176 @Test177 public void testProduceOutputShortMessage() throws Exception {178 final BasicHttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK");179 final NStringEntity entity = new NStringEntity("stuff");180 response.setEntity(entity);181 final WritableByteChannelMock wchannel = Mockito.spy(new WritableByteChannelMock(64));182 final ByteChannelMock channel = new ByteChannelMock(null, wchannel);183 Mockito.when(session.channel()).thenReturn(channel);184 Mockito.doAnswer(new ResponseReadyAnswer(response)).when(185 handler).responseReady(Mockito.<NHttpServerConnection>any());186 Mockito.doAnswer(new ProduceContentAnswer(entity)).when(187 handler).outputReady(Mockito.<NHttpServerConnection>any(), Mockito.<ContentEncoder>any());188 conn.produceOutput(handler);189 Assert.assertNull(conn.getHttpResponse());190 Assert.assertNull(conn.contentEncoder);191 Assert.assertEquals("HTTP/1.1 200 OK\r\n\r\nstuff", wchannel.dump(Consts.ASCII));192 Mockito.verify(wchannel, Mockito.times(1)).write(Matchers.<ByteBuffer>any());193 }194 @Test195 public void testProduceOutputLongMessage() throws Exception {196 final BasicHttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK");197 final NStringEntity entity = new NStringEntity("a lot of various stuff");198 response.setEntity(entity);199 final WritableByteChannelMock wchannel = Mockito.spy(new WritableByteChannelMock(64));200 final ByteChannelMock channel = new ByteChannelMock(null, wchannel);201 Mockito.when(session.channel()).thenReturn(channel);202 Mockito.doAnswer(new ResponseReadyAnswer(response)).when(203 handler).responseReady(Mockito.<NHttpServerConnection>any());204 Mockito.doAnswer(new ProduceContentAnswer(entity)).when(205 handler).outputReady(Mockito.<NHttpServerConnection>any(), Mockito.<ContentEncoder>any());206 conn.produceOutput(handler);207 Assert.assertNull(conn.getHttpResponse());208 Assert.assertNull(conn.contentEncoder);209 Assert.assertEquals("HTTP/1.1 200 OK\r\n\r\na lot of various stuff", wchannel.dump(Consts.ASCII));210 Mockito.verify(wchannel, Mockito.times(2)).write(Matchers.<ByteBuffer>any());211 }212 @Test213 public void testProduceOutputLongMessageSaturatedChannel() throws Exception {214 final BasicHttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK");215 final NStringEntity entity = new NStringEntity("a lot of various stuff");216 response.setEntity(entity);217 final WritableByteChannelMock wchannel = Mockito.spy(new WritableByteChannelMock(64, 24));218 final ByteChannelMock channel = new ByteChannelMock(null, wchannel);219 Mockito.when(session.channel()).thenReturn(channel);220 Mockito.doAnswer(new ResponseReadyAnswer(response)).when(221 handler).responseReady(Mockito.<NHttpServerConnection>any());222 Mockito.doAnswer(new ProduceContentAnswer(entity)).when(223 handler).outputReady(Mockito.<NHttpServerConnection>any(), Mockito.<ContentEncoder>any());224 conn.produceOutput(handler);225 Assert.assertNull(conn.getHttpResponse());226 Assert.assertNull(conn.contentEncoder);227 Assert.assertEquals("HTTP/1.1 200 OK\r\n\r\na lot", wchannel.dump(Consts.ASCII));228 Assert.assertEquals(17, conn.outbuf.length());229 Mockito.verify(session, Mockito.never()).clearEvent(SelectionKey.OP_WRITE);230 Mockito.verify(wchannel, Mockito.times(2)).write(Matchers.<ByteBuffer>any());231 }232 @Test233 public void testProduceOutputLongMessageSaturatedChannel2() throws Exception {234 conn = new DefaultNHttpServerConnection(session, 24);235 final BasicHttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK");236 final NStringEntity entity = new NStringEntity("a loooooooooooooooooooooooot of various stuff");237 response.setEntity(entity);238 final WritableByteChannelMock wchannel = Mockito.spy(new WritableByteChannelMock(64, 24));239 final ByteChannelMock channel = new ByteChannelMock(null, wchannel);240 Mockito.when(session.channel()).thenReturn(channel);241 Mockito.doAnswer(new ResponseReadyAnswer(response)).when(242 handler).responseReady(Mockito.<NHttpServerConnection>any());243 Mockito.doAnswer(new ProduceContentAnswer(entity)).when(244 handler).outputReady(Mockito.<NHttpServerConnection>any(), Mockito.<ContentEncoder>any());245 conn.produceOutput(handler);246 Assert.assertNotNull(conn.getHttpResponse());247 Assert.assertNotNull(conn.contentEncoder);248 Assert.assertEquals("HTTP/1.1 200 OK\r\n\r\na loo", wchannel.dump(Consts.ASCII));249 Mockito.verify(session, Mockito.never()).clearEvent(SelectionKey.OP_WRITE);250 Mockito.verify(wchannel, Mockito.times(3)).write(Matchers.<ByteBuffer>any());251 }252 @Test253 public void testProduceOutputLongChunkedMessage() throws Exception {254 conn = new DefaultNHttpServerConnection(session, 64);255 final BasicHttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK");256 response.addHeader(HTTP.TRANSFER_ENCODING, HTTP.CHUNK_CODING);257 final NStringEntity entity = new NStringEntity("a lot of various stuff");258 entity.setChunked(true);259 response.setEntity(entity);260 final WritableByteChannelMock wchannel = Mockito.spy(new WritableByteChannelMock(64));261 final ByteChannelMock channel = new ByteChannelMock(null, wchannel);262 Mockito.when(session.channel()).thenReturn(channel);263 Mockito.doAnswer(new ResponseReadyAnswer(response)).when(264 handler).responseReady(Mockito.<NHttpServerConnection>any());265 Mockito.doAnswer(new ProduceContentAnswer(entity)).when(266 handler).outputReady(Mockito.<NHttpServerConnection>any(), Mockito.<ContentEncoder>any());267 conn.produceOutput(handler);268 Assert.assertNull(conn.getHttpResponse());269 Assert.assertNull(conn.contentEncoder);270 Assert.assertEquals("HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n" +271 "5\r\na lot\r\n11\r\n of various stuff\r\n0\r\n\r\n", wchannel.dump(Consts.ASCII));272 Mockito.verify(wchannel, Mockito.times(2)).write(Matchers.<ByteBuffer>any());273 }274 @Test275 public void testProduceOutputLongChunkedMessageSaturatedChannel() throws Exception {276 conn = new DefaultNHttpServerConnection(session, 64);277 final BasicHttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK");278 response.addHeader(HTTP.TRANSFER_ENCODING, HTTP.CHUNK_CODING);279 final NStringEntity entity = new NStringEntity("a lot of various stuff");280 entity.setChunked(true);281 response.setEntity(entity);282 final WritableByteChannelMock wchannel = Mockito.spy(new WritableByteChannelMock(64, 64));283 final ByteChannelMock channel = new ByteChannelMock(null, wchannel);284 Mockito.when(session.channel()).thenReturn(channel);285 Mockito.doAnswer(new ResponseReadyAnswer(response)).when(286 handler).responseReady(Mockito.<NHttpServerConnection>any());287 Mockito.doAnswer(new ProduceContentAnswer(entity)).when(288 handler).outputReady(Mockito.<NHttpServerConnection>any(), Mockito.<ContentEncoder>any());289 conn.produceOutput(handler);290 Assert.assertNull(conn.getHttpResponse());291 Assert.assertNull(conn.contentEncoder);292 Assert.assertEquals("HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n" +293 "5\r\na lot\r\n11\r\n of", wchannel.dump(Consts.ASCII));294 Assert.assertEquals(21, conn.outbuf.length());295 Mockito.verify(session, Mockito.never()).clearEvent(SelectionKey.OP_WRITE);296 Mockito.verify(wchannel, Mockito.times(2)).write(Matchers.<ByteBuffer>any());297 }298 @Test299 public void testProduceOutputClosingConnection() throws Exception {300 final BasicHttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK");301 final WritableByteChannelMock wchannel = Mockito.spy(new WritableByteChannelMock(64));302 final ByteChannelMock channel = new ByteChannelMock(null, wchannel);303 Mockito.when(session.channel()).thenReturn(channel);304 conn.submitResponse(response);305 conn.close();306 Assert.assertEquals(NHttpConnection.CLOSING, conn.getStatus());307 conn.produceOutput(handler);308 Assert.assertEquals(NHttpConnection.CLOSED, conn.getStatus());309 Mockito.verify(wchannel, Mockito.times(1)).write(Matchers.<ByteBuffer>any());310 Mockito.verify(session, Mockito.times(1)).close();311 Mockito.verify(session, Mockito.never()).clearEvent(SelectionKey.OP_WRITE);312 Mockito.verify(handler, Mockito.never()).responseReady(313 Mockito.<NHttpServerConnection>any());314 Mockito.verify(handler, Mockito.never()).outputReady(315 Mockito.<NHttpServerConnection>any(), Mockito.<ContentEncoder>any());316 }317 static class RequestCapturingAnswer implements Answer<Void> {318 private final LinkedList<HttpRequest> requests;319 RequestCapturingAnswer(final LinkedList<HttpRequest> requests) {320 super();321 this.requests = requests;322 }323 @Override324 public Void answer(final InvocationOnMock invocation) throws Throwable {325 final Object[] args = invocation.getArguments();326 final NHttpServerConnection conn = (NHttpServerConnection) args[0];327 if (conn != null) {328 final HttpRequest request = conn.getHttpRequest();329 if (request != null) {330 requests.add(request);331 }332 }333 return null;334 }335 }336 static class ConsumeContentAnswer implements Answer<Void> {337 private final SimpleInputBuffer buf;338 ConsumeContentAnswer(final SimpleInputBuffer buf) {339 super();340 this.buf = buf;341 }342 @Override343 public Void answer(final InvocationOnMock invocation) throws Throwable {344 final Object[] args = invocation.getArguments();345 final ContentDecoder decoder = (ContentDecoder) args[1];346 buf.consumeContent(decoder);347 return null;348 }349 }350 @Test351 public void testConsumeInputShortMessage() throws Exception {352 final ReadableByteChannelMock rchannel = Mockito.spy(new ReadableByteChannelMock(353 new String[] {"POST / HTTP/1.1\r\nContent-Length: 5\r\n\r\nstuff"}, Consts.ASCII));354 final ByteChannelMock channel = new ByteChannelMock(rchannel, null);355 Mockito.when(session.channel()).thenReturn(channel);356 Mockito.when(session.getEventMask()).thenReturn(SelectionKey.OP_READ);357 final LinkedList<HttpRequest> requests = new LinkedList<HttpRequest>();...

Full Screen

Full Screen

Source:OfficalTest_Part_2.java Github

copy

Full Screen

...36 public void step_11() {37 final LinkedList mockedLinkList = mock(LinkedList.class);38 when(mockedLinkList.remove(anyInt())).thenAnswer(new Answer<String>() {39 @Override40 public String answer(InvocationOnMock invocation) throws Throwable {41 Object[] arguments = invocation.getArguments();42 Object mock = invocation.getMock();43 return "called with arguments: " + Arrays.toString(arguments);44 }45 });46 System.out.println(mockedLinkList.remove(999));47 }48 /*49 * doReturn()|doThrow()| doAnswer()|doNothing()|doCallRealMethod() family of methods50 *51 */52 /**53 * {@see Mockito54 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#1255 * }56 */57 @Test58 public void step_12() {59 final LinkedList mockedLinkList = mock(LinkedList.class);60 when(mockedLinkList.get(0)).thenReturn(false);61 doAnswer(new Answer<Boolean>() {62 @Override63 public Boolean answer(InvocationOnMock invocation) throws Throwable {64 Object[] arguments = invocation.getArguments();65 Object mock = invocation.getMock();66 return mock == mockedLinkList;67 }68 }).when(mockedLinkList).get(anyInt());69 System.out.println(mockedLinkList.get(0));70 }71 /*72 * 当使用spy的时候,会真正调用相应的方法(除非使用其他手段修改相应的返回值, 比如doXxx())73 * 注意:应当尽可能仔细使用,并且尽量少地使用spy,比如在处理遗留的代码的时候74 * 在一个真正的对象上使用Spy,可以理解为“partial mocking”;但是在1.8之前,Mockito并不是真正75 * partial mock,原因在于,我们认为partial mock是代码的一部分。在某些方面,我们发现了使用部分mocks76 * 的合理之处(例如:第三方接口,遗留代码的临时重构,全部的文章,参考以下内容77 * {@see partial-mocking78 * https://monkeyisland.pl/2009/01/13/subclass-and-override-vs-partial-mocking-vs-refactoring/})79 * 有一点需要特别注意的是,在使用 when(Object)方法调用spy对象的时候,建议使用以下的方法替代doReturn|Answer|Throw()80 * 例如81 * //Impossible: real method is called so spy.get(0) throws IndexOutOfBoundsException (the list is yet empty)82 * when(spy.get(0)).thenReturn("ArrayList");83 * 由于spy并没有初始化,因此将会抛出相应的异常84 * //You have to use doReturn() for stubbing85 * doReturn("ArrayList").when(spy).get(0);86 *87 */88 /**89 * {@see Mockito90 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#1391 * }92 */93 @Test94 public void step_13() {95 List list = new LinkedList();96 List<String> spy = spy(list);97 //Impossible: real method is called so spy.get(0) throws IndexOutOfBoundsException (the list is yet empty)98 when(spy.get(0)).thenReturn("ArrayList");99 //You have to use doReturn() for stubbing100 doReturn("ArrayList").when(spy).get(0);101 //optionally, you can stub out some methods:102 when(spy.size()).thenReturn(100);103 //using the spy calls *real* methods104 spy.add("one");105 spy.add("two");106 //prints "one" - the first element of a list107 System.out.println(spy.get(0));108 //size() method was stubbed - 100 is printed109 System.out.println(spy.size());110 //optionally, you can verify111 verify(spy).add("one");112 verify(spy).add("two");113 }114 /*115 * Changing default return values of unstubbed invocations (Since 1.7)116 * 我们可以给相应的返回值,指定一个默认的规则。117 * 这是想当高级的功能,并且对于旧系统,来说是非常有帮助的118 * 默认情况下,你根本不需要调用它119 * 更多的内容,可以参考默认的实现。120 * {@see RETURNS_SMART_NULLS121 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#RETURNS_SMART_NULLS122 * }123 */124 /**125 * {@see Mockito126 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#14127 * }128 */129 @Test130 public void step_14() {131 List mock = mock(ArrayList.class, Mockito.RETURNS_SMART_NULLS);132 List mockTwo = mock(List.class, new Answer() {133 @Override134 public Object answer(InvocationOnMock invocation) throws Throwable {135 return false;136 }137 });138 System.out.println( mockTwo.add("haha"));139 }140 /*141 * Capturing arguments for further assertions (Since 1.8.0)142 * 这个功能,可以帮助你检验相应的参数的正确性143 * 警告:必须记住的是使用ArgumentCaptor 功能应该是检验而不是用来替代默认值。144 * 如果使用ArgumentCaptor 将减少代码的可读性,因为捕获是在assert之外创建,145 * (例如在aka verify 或者‘then’)146 * 它同时减少了定位缺陷,因为如果stubbed方法没有被调用,那么将不会有参数被捕获147 * ArgumentCaptor 更适用于以下情形:148 * 1、自定义argument matcher不太可能被重用...

Full Screen

Full Screen

Source:OfficalTest_Part_4.java Github

copy

Full Screen

...8public class OfficalTest_Part_4 {9 /*10 * Mockito mocks can be serialized / deserialized across classloaders (Since 1.10.0)11 * Mockito实现了从classloader中引入序列化。就好像任何对象来自于系列化之中,在mock层次中的所有12 * 类型都必须序列化,并且包含answers;13 * 还可以参考以下内容14 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/MockSettings.html#serializable(org.mockito.mock.SerializableMode)15 */16 /**17 * {@see Mockito18 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#3119 * }20 */21 @Test22 public void step_31() {23// // use regular serialization24// mock(Book.class, withSettings().serializable());25//26// // use serialization across classloaders27// mock(Book.class, withSettings().serializable(ACROSS_CLASSLOADERS));28 }29 /*30 * Better generic support with deep stubs (Since 1.10.0)31 * 在类中如果泛型信息被引入,这就意味着类可以这样被使用而没有mock行为。32 *33 * 注意:34 * 在大多数情况下,mock返回mock对象是错误的。35 */36 /**37 * {@see Mockito38 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#3239 * }40 */41 @Test42 public void step_32() {43//44// class Lines extends List<Line> {45// // ...46// }47//48// lines = mock(Lines.class, RETURNS_DEEP_STUBS);49//50// // Now Mockito understand this is not an Object but a Line51// Line line = lines.iterator().next();52 }53 /*54 * Mockito JUnit rule (Since 1.10.17)55 * 在初始化注解中比如@Mock @Spy @InjectMocks有两种手段与方法56 * 1、使用@RunWith(MockitoJUnitRunner.class)注解JUnit测试类57 * 2、在使用@Before注解的方法中使用MockitoAnnotations.initMocks(Object)58 * Mockito.rule()59 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/junit/MockitoJUnit.html#rule()60 */61 /**62 * {@see Mockito63 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#64 * }65 */66 @Test67 public void step_33() {68// @RunWith(YetAnotherRunner.class)69// public class TheTest {70// @Rule public MockitoRule mockito = MockitoJUnit.rule();71// // ...72// }73 }74 /*75 * Switch on or off plugins (Since 1.10.15)76 * 一个孵化功能使它在mockito的方式,将允许切换mockito插件。77 * PluginSwitch78 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/plugins/PluginSwitch.html79 */80 /**81 * {@see Mockito82 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#83 * }84 */85 @Test86 public void step_34() {87 }88 /*89 * Custom verification failure message (Since 2.1.0)90 * 如果校验失败的话,可以自定义的提示信息。91 */92 /**93 * {@see Mockito94 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#3595 * }96 */97 @Test98 public void step_35() {99 ArrayList mock = mock(ArrayList.class);100 // will print a custom message on verification failure101 verify(mock, description("This will print on failure")).clear();102 // will work with any verification mode103 verify(mock, times(2).description("someMethod should be called twice")).size();104 }105 /*106 * Java 8 Lambda Matcher Support (Since 2.1.0)107 *108 */109 /**110 * {@see Mockito111 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#36112 * }113 */114 @Test115 public void step_36() {116//117// // verify a list only had strings of a certain length added to it118// // note - this will only compile under Java 8119// verify(list, times(2)).add(argThat(string -> string.length() < 5));120//121// // Java 7 equivalent - not as neat122// verify(list, times(2)).add(argThat(new ArgumentMatcher(){123// public boolean matches(String arg) {124// return arg.length() < 5;125// }126// }));127//128// // more complex Java 8 example - where you can specify complex verification behaviour functionally129// verify(target, times(1)).receiveComplexObject(argThat(obj -> obj.getSubObject().get(0).equals("expected")));130//131// // this can also be used when defining the behaviour of a mock under different inputs132// // in this case if the input list was fewer than 3 items the mock returns null133// when(mock.someMethod(argThat(list -> list.size()<3))).willReturn(null);134 }135 /*136 *137 */138 /**139 * {@see Mockito140 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#37141 * }142 */143 @Test144 public void step_37() {145// // answer by returning 12 every time146// doAnswer(invocation -> 12).when(mock).doSomething();147//148// // answer by using one of the parameters - converting into the right149// // type as your go - in this case, returning the length of the second string parameter150// // as the answer. This gets long-winded quickly, with casting of parameters.151// doAnswer(invocation -> ((String)invocation.getArgument(1)).length())152// .when(mock).doSomething(anyString(), anyString(), anyString());153//154// // Example interface to be mocked has a function like:155// void execute(String operand, Callback callback);156//157// // the example callback has a function and the class under test158// // will depend on the callback being invoked159// void receive(String item);160//161// // Java 8 - style 1162// doAnswer(AdditionalAnswers.answerVoid((operand, callback) -> callback.receive("dummy"))163// .when(mock).execute(anyString(), any(Callback.class));164//165// // Java 8 - style 2 - assuming static import of AdditionalAnswers166// doAnswer(answerVoid((String operand, Callback callback) -> callback.receive("dummy"))167// .when(mock).execute(anyString(), any(Callback.class));168//169// // Java 8 - style 3 - where mocking function to is a static member of test class170// private static void dummyCallbackImpl(String operation, Callback callback) {171// callback.receive("dummy");172// }173//174// doAnswer(answerVoid(TestClass::dummyCallbackImpl)175// .when(mock).execute(anyString(), any(Callback.class));176//177// // Java 7178// doAnswer(answerVoid(new VoidAnswer2() {179// public void answer(String operation, Callback callback) {180// callback.receive("dummy");181// }})).when(mock).execute(anyString(), any(Callback.class));182//183// // returning a value is possible with the answer() function184// // and the non-void version of the functional interfaces185// // so if the mock interface had a method like186// boolean isSameString(String input1, String input2);187//188// // this could be mocked189// // Java 8190// doAnswer(AdditionalAnswers.answer((input1, input2) -> input1.equals(input2))))191// .when(mock).execute(anyString(), anyString());192//193// // Java 7194// doAnswer(answer(new Answer2() {195// public String answer(String input1, String input2) {196// return input1 + input2;197// }})).when(mock).execute(anyString(), anyString());198 }199 /*200 * Meta data and generic type retention (Since 2.1.0)201 * Mockito现在保留mocked方法以及类型上的注释信息,就像作为泛型属性数据一样。202 * 以前,模拟类型没有保留对类型的注释,除非它们被显式地继承,并且从未在方法上保留注释。203 * 因此,现在的条件如下:204 * 当时用Java8时,Mockito现在也会保留类型注解,这是默认行为,如果使用另一个MockMaker可能不会保留。205 */206 /**207 * {@see Mockito208 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#38209 * }...

Full Screen

Full Screen

Source:FollowingPresenterTest.java Github

copy

Full Screen

...60 public void testLoadMoreItems_CorrectParamsPassedToStatusService() {61 List<User> followees = Arrays.asList(user1, user2, user3, user4, user5);62 Answer<Void> manyFolloweesAnswer = new Answer<Void>() {63 @Override64 public Void answer(InvocationOnMock invocation) throws Throwable {65 AuthToken authToken = invocation.getArgument(0);66 User user = invocation.getArgument(1);67 int limit = invocation.getArgument(2);68 User lastFollowee = invocation.getArgument(3);69 // Assert that the parameters are correct70 Assert.assertEquals(fakeUser, user);71 Assert.assertEquals(fakeAuthToken, authToken);72 Assert.assertEquals(limit, FollowingPresenter.PAGE_SIZE);73 Assert.assertEquals(lastFollowee, followingPresenterSpy.lastItem);74 PagedNotificationObserver<User> observer = invocation.getArgument(4);75 observer.handleSuccess(followees, true);76 return null;77 }78 };79 Mockito.doAnswer(manyFolloweesAnswer).when(followingServiceMock).getFollowing(Mockito.any(), Mockito.any(), Mockito.anyInt(), Mockito.any(), Mockito.any());80 followingPresenterSpy.loadItems(fakeUser);81 }82/**83 * Verify that {@link FollowingPresenter#loadItems(User)} works correctly when there84 * are some pages of followees.85 */86 @Test87 public void testLoadMoreItems_GetFolloweesSuccess() throws InterruptedException {88 List<User> followees = Arrays.asList(user1, user2, user3, user4, user5);89 Answer<Void> manyFolloweesAnswer = new Answer<Void>() {90 @Override91 public Void answer(InvocationOnMock invocation) throws Throwable {92 PagedNotificationObserver<User> observer = invocation.getArgument(4);93 observer.handleSuccess(followees, true);94 return null;95 }96 };97 Mockito.doAnswer(manyFolloweesAnswer).when(followingServiceMock).getFollowing(Mockito.any(), Mockito.any(), Mockito.anyInt(), Mockito.any(), Mockito.any());98 followingPresenterSpy.loadItems(fakeUser);99 assertEquals(user5, followingPresenterSpy.lastItem);100 assertTrue(followingPresenterSpy.hasMorePages);101 assertFalse(followingPresenterSpy.isLoading());102 Mockito.verify(followingViewMock).setLoadingStatus(true);103 Mockito.verify(followingViewMock).setLoadingStatus(false);104 Mockito.verify(followingViewMock).addItems(Arrays.asList(user1, user2, user3, user4, user5));105 }106/**107 * Verify that {@link FollowingPresenter#loadItems(User)} works correctly when there108 * are between two and three pages of followees.109 */110 @Test111 public void testLoadMoreItems_GetFolloweesFailsWithErrorMessage() throws InterruptedException {112 Answer<Void> failureAnswer = new Answer<Void>() {113 @Override114 public Void answer(InvocationOnMock invocation) throws Throwable {115 PagedNotificationObserver<User> observer = invocation.getArgument(4);116 observer.handleFailure("failure message");117 return null;118 }119 };120 Mockito.doAnswer(failureAnswer).when(followingServiceMock).getFollowing(Mockito.any(), Mockito.any(), Mockito.anyInt(), Mockito.any(), Mockito.any());121 followingPresenterSpy.loadItems(fakeUser);122 assertFalse(followingPresenterSpy.isLoading());123 Mockito.verify(followingViewMock).setLoadingStatus(true);124 Mockito.verify(followingViewMock).setLoadingStatus(false);125 Mockito.verify(followingViewMock).displayErrorMessage("Failed to retrieve followees: " + "failure message");126 Mockito.verify(followingViewMock, Mockito.times(0)).addItems(Mockito.any());127 }128 @Test129 public void testLoadMoreItems_GetFolloweesFailsWithExceptionMessage() throws InterruptedException {130 Answer<Void> exceptionAnswer = new Answer<Void>() {131 @Override132 public Void answer(InvocationOnMock invocation) throws Throwable {133 PagedNotificationObserver<User> observer = invocation.getArgument(4);134 observer.handleException(new Exception("The exception message"));135 return null;136 }137 };138 Mockito.doAnswer(exceptionAnswer).when(followingServiceMock).getFollowing(Mockito.any(), Mockito.any(), Mockito.anyInt(), Mockito.any(), Mockito.any());139 followingPresenterSpy.loadItems(fakeUser);140 assertFalse(followingPresenterSpy.isLoading());141 Mockito.verify(followingViewMock).setLoadingStatus(true);142 Mockito.verify(followingViewMock).setLoadingStatus(false);143 Mockito.verify(followingViewMock).displayErrorMessage("Failed to retrieve followees because of exception: " + "The exception message");144 Mockito.verify(followingViewMock, Mockito.times(0)).addItems(Mockito.any());145 }146}...

Full Screen

Full Screen

Source:MainPresenterUnitTest.java Github

copy

Full Screen

...43 basicPostStatusTest(TestStatus.exception);44 Mockito.verify(mockView).displayErrorMessage("Failed to get post status because of exception: exception message");45 }46 private void basicPostStatusTest(TestStatus pass) {47 Answer<Void> answer = getPostStatusAnswer(pass);48 Mockito.doAnswer(answer).when(mockStatusService).postStatus(Mockito.any(), Mockito.any());49 mainPresenterSpy.postStatus("Hello", "12pm", null, null);50 Mockito.verify(mockView).displayInfoMessage("Posting Status");51 Mockito.verify(mockStatusService).postStatus(Mockito.any(), Mockito.any());52 }53 private Answer<Void> getPostStatusAnswer(TestStatus result) {54 Answer<Void> answer = new Answer<Void>() {55 @Override56 public Void answer(InvocationOnMock invocation) throws Throwable {57 Status testStatus = invocation.getArgument(0);58 Assert.assertSame(testStatus.getClass(), Status.class);59 Assert.assertNotNull(testStatus);60 SimpleNotificationObserver observer = invocation.getArgument(1, SimpleNotificationObserver.class);61 Assert.assertSame(observer.getClass(), MainPresenter.PostStatusObserver.class);62 Assert.assertNotNull(observer);63 if (result == TestStatus.pass)64 observer.handleSuccess();65 else if(result == TestStatus.fail)66 observer.handleFailure("Failed to post");67 else68 observer.handleException(new Exception("exception message"));69 return null;70 }71 };72 return answer;73 }74 private enum TestStatus{75 fail,76 pass,77 exception78 }79 @Test80 public void testLogout_success(){81 Answer<Void> answer = new Answer<Void>() {82 @Override83 public Void answer(InvocationOnMock invocation) throws Throwable {84 SimpleNotificationObserver observer = invocation.getArgument(1, SimpleNotificationObserver.class);85 observer.handleSuccess();86 return null;87 }88 };89 Mockito.doAnswer(answer).when(mockLoginService).logout(Mockito.any(), Mockito.any());90 mainPresenterSpy.logout();91 Mockito.verify(mockView).displayInfoMessage("Logging Out");92 Mockito.verify(mockCache).clearCache();93 Mockito.verify(mockView).clearInfoMessage();94 Mockito.verify(mockView).logoutSuccessful();95 }96 @Test97 public void testLogout_failWithMessage(){98 Answer<Void> answer = new Answer<Void>() {99 @Override100 public Void answer(InvocationOnMock invocation) throws Throwable {101 SimpleNotificationObserver observer = invocation.getArgument(1, SimpleNotificationObserver.class);102 observer.handleFailure("failure");103 return null;104 }105 };106 Mockito.doAnswer(answer).when(mockLoginService).logout(Mockito.any(), Mockito.any());107 mainPresenterSpy.logout();108 Mockito.verify(mockView).displayInfoMessage("Logging Out");109 Mockito.verify(mockCache, Mockito.times(0)).clearCache();110 Mockito.verify(mockView).clearInfoMessage();111 Mockito.verify(mockView).displayErrorMessage("Failed to get logout: failure");112 }113 @Test114 public void testLogout_failWithException(){115 Answer<Void> answer = new Answer<Void>() {116 @Override117 public Void answer(InvocationOnMock invocation) throws Throwable {118 SimpleNotificationObserver observer = invocation.getArgument(1, SimpleNotificationObserver.class);119 observer.handleException(new Exception("the message from the exception"));120 return null;121 }122 };123 Mockito.doAnswer(answer).when(mockLoginService).logout(Mockito.any(), Mockito.any());124 mainPresenterSpy.logout();125 Mockito.verify(mockView).displayInfoMessage("Logging Out");126 Mockito.verify(mockCache, Mockito.times(0)).clearCache();127 Mockito.verify(mockView).clearInfoMessage();128 Mockito.verify(mockView).displayErrorMessage("Failed to get logout because of exception: the message from the exception");129 }130}...

Full Screen

Full Screen

Source:BaseUnitTest.java Github

copy

Full Screen

...37 when(PreferenceManager.getDefaultSharedPreferences(any(Context.class))).thenReturn(sharedPreferences);38 when(Looper.getMainLooper()).thenReturn(null);39 PowerMockito.whenNew(Handler.class).withAnyArguments().thenReturn(null);40 Answer<?> logAnswer = new Answer<Void>() {41 @Override public Void answer(InvocationOnMock invocation) throws Throwable {42 final String tag = (String)invocation.getArguments()[0];43 final String msg = (String)invocation.getArguments()[1];44 System.out.println(invocation.getMethod().getName().toUpperCase() + "/[" + tag + "] " + msg);45 return null;46 }47 };48 PowerMockito.doAnswer(logAnswer).when(Log.class, "d", anyString(), anyString());49 PowerMockito.doAnswer(logAnswer).when(Log.class, "i", anyString(), anyString());50 PowerMockito.doAnswer(logAnswer).when(Log.class, "w", anyString(), anyString());51 PowerMockito.doAnswer(logAnswer).when(Log.class, "e", anyString(), anyString());52 PowerMockito.doAnswer(new Answer<Boolean>() {53 @Override54 public Boolean answer(InvocationOnMock invocation) throws Throwable {55 final String s = (String)invocation.getArguments()[0];56 return s == null || s.length() == 0;57 }58 }).when(TextUtils.class, "isEmpty", anyString());59 when(sharedPreferences.getString(anyString(), anyString())).thenReturn("");60 when(sharedPreferences.getLong(anyString(), anyLong())).thenReturn(0L);61 when(sharedPreferences.getInt(anyString(), anyInt())).thenReturn(0);62 when(sharedPreferences.getBoolean(anyString(), anyBoolean())).thenReturn(false);63 when(sharedPreferences.getFloat(anyString(), anyFloat())).thenReturn(0f);64 when(context.getSharedPreferences(anyString(), anyInt())).thenReturn(sharedPreferences);65 when(context.getPackageName()).thenReturn("org.thoughtcrime.securesms");66 }67}...

Full Screen

Full Screen

Source:StaticMethodTest.java Github

copy

Full Screen

...394041 // PowerMockito.doAnswer(new Answer() {42 // @Override43 // public Object answer(InvocationOnMock invocation) throws Throwable {44 // int i = (int) invocation.getArguments()[0];45 // System.out.println(i);46 // return i;47 // }48 //49 // }).when(Foo.staticInput(anyInt()));50 */5152 System.out.println(Foo.static1());53 System.out.println(Foo.static2());54 System.out.println(Foo.staticInput(7));5556 }5758 @Test59 public void testFileTemp() throws Exception {606162 PowerMockito.mockStatic(File.class);63 // PowerMockito.doReturn("dummy").when(Foo.class, "static1");64 // PowerMockito.doReturn(new File("aaa")).when(File.createTempFile("aa", "bbb"));65// PowerMockito.when(File.createTempFile(anyString(), anyString())).thenAnswer(invocation -> {66// //System.out.println((int)invocation.getArgument(0));67//// return "staticInput mock";68// return new File("aaa");69// });7071// PowerMockito.mockStatic(File.class);72 File mockFile = PowerMockito.mock(File.class);73 PowerMockito.when(File.createTempFile(anyString(), anyString())).thenReturn(mockFile);7475 File f = File.createTempFile("aa", "bbb");7677 //PowerMockito.doReturn(4).when(Foo.class, "staticInput", anyInt());7879 // PowerMockito.do8081 /*PowerMockito.when(Foo.staticInput(anyInt())).thenAnswer(invocation -> {82 System.ou/838485 // PowerMockito.doAnswer(new Answer() {86 // @Override87 // public Object answer(InvocationOnMock invocation) throws Throwable {88 // int i = (int) invocation.getArguments()[0];89 // System.out.println(i);90 // return i;91 // }92 //93 // }).when(Foo.staticInput(anyInt()));94 */95969798 }99100101} ...

Full Screen

Full Screen

answer

Using AI Code Generation

copy

Full Screen

1import static org.mockito.Mockito.*;2import java.util.List;3public class 1 {4 List mockedList = mock(List.class);5 mockedList.add("one");6 mockedList.clear();7 verify(mockedList).add("one");8 verify(mockedList).clear();9}10import static org.mockito.Mockito.*;11import java.util.List;12public class 2 {13 LinkedList mockedList = mock(LinkedList.class);14 when(mockedList.get(0)).thenReturn("first");15 when(mockedList.get(1)).thenThrow(new RuntimeException());16 System.out.println(mockedList.get(0));17 System.out.println(mockedList.get(1));18 System.out.println(mockedList.get(999));19 verify(mockedList).get(0);20}21import static org.mockito.Mockito.*;22import java.util.List;23public class 3 {24 List singleMock = mock(List.class);25 singleMock.add("was added first");26 singleMock.add("was added second");27 InOrder inOrder = inOrder(singleMock);28 inOrder.verify(singleMock).add("was added first");29 inOrder.verify(singleMock).add("was added second");30 List firstMock = mock(List.class);

Full Screen

Full Screen

answer

Using AI Code Generation

copy

Full Screen

1import org.mockito.Mockito;2import static org.mockito.Mockito.*;3import org.mockito.invocation.InvocationOnMock;4import org.mockito.stubbing.Answer;5public class 1 {6 public static void main(String[] args) {7 List mockedList = mock(List.class);8 when(mockedList.get(anyInt())).thenAnswer(new Answer() {9 public Object answer(InvocationOnMock invocation) throws Throwable {10 Object[] args = invocation.getArguments();11 Object mock = invocation.getMock();12 return "called with arguments: " + args;13 }14 });15 System.out.println(mockedList.get(0));16 System.out.println(mockedList.get(1));17 }18}19Recommended Posts: Mockito - doAnswer() Method20Mockito - doReturn() Method21Mockito - doThrow() Method22Mockito - doNothing() Method23Mockito - doCallRealMethod() Method24Mockito - doAnswer() and doReturn() Method25Mockito - doThrow() and doNothing() Method26Mockito - doCallRealMethod() and doAnswer() Method27Mockito - doThrow() and doNothing() Method28Mockito - doCallRealMethod() and doReturn() Method29Mockito - doThrow() and doReturn() Method30Mockito - doNothing() and doReturn() Method31Mockito - doCallRealMethod() and doNothing() Method32Mockito - doThrow() and doCallRealMethod() Method33Mockito - doNothing() and doCallRealMethod() Method34Mockito - doReturn() and doCallRealMethod() Method35Mockito - doReturn() and doThrow() Method36Mockito - doNothing() and doThrow() Method37Mockito - doCallRealMethod() and doThrow() Method38Mockito - doReturn() and doNothing() Method39Mockito - doAnswer() and doThrow() Method40Mockito - doAnswer() and doNothing() Method41Mockito - doAnswer() and doCallRealMethod() Method42Mockito - doReturn() and doCall

Full Screen

Full Screen

answer

Using AI Code Generation

copy

Full Screen

1import static org.mockito.Mockito.*;2import org.mockito.*;3import org.mockito.stubbing.*;4import org.mockito.invocation.*;5import org.mockito.verification.*;6import org.mockito.exceptions.*;7import org.mockito.matchers.*;8import org.mockito.listeners.*;9import org.mockito.cglib.*;10import org.mockito.cglib.proxy.*;11import org.mockito.cglib.core.*;12import org.mockito.asm.*;13import org.mockito.asm.commons.*;14import org.mockito.asm.tree.*;15import org.mockito.asm.util.*;16import org.mockito.asm.signature.*;17import org.mockito.asm.tree.analysis.*;18import org.mockito.asm.tree.analysis.Frame;19import org.mockito.asm.tree.analysis.Interpreter;20import org.mockito.asm.tree.analysis.Value;21import org.mockito.asm.util.ASMifiable;22import org.mockito.asm.util.ASMifier;23import org.mockito.asm.util.CheckClassAdapter;24import org.mockito.asm.util.CheckFieldAdapter;25import org.mockito.asm.util.CheckMethodAdapter;26import org.mockito.asm.util.Printer;27import org.mockito.asm.util.Textifier;28import org.mockito.asm.util.TraceAnnotationVisitor;29import org.mockito.asm.util.TraceClassVisitor;30import org.mockito.asm.util.TraceFieldVisitor;31import org.mockito.asm.util.TraceMethodVisitor;32import org.mockito.asm.util.TraceSignatureVisitor;33import org.mockito.asm.util.Traceable;34import org.mockito.internal.*;35import org.mockito.internal.matchers.*;36import org.mockito.internal.matchers.apachecommons.ReflectionEquals;37import org.mockito.internal.matchers.apachecommons.ReflectionEquals.*;38import org.mockito.internal.matchers.apachecommons.ReflectionToStringBuilder;39import org.mockito.internal.matchers.apachecommons.ReflectionToStringBuilder.*;40import org.mockito.internal.progress.*;41import org.mockito.internal.progress.MockingProgress;42import org.mockito.internal.progress.MockingProgressImpl;43import org.mockito.internal.progress.ThreadSafeMockingProgress;44import org.mockito.internal.stubbing.answers.Returns;45import org.mockito.internal.stubbing.answers.ReturnsEmptyValues;46import org.mockito.internal.stubbing.answers.ReturnsMoreEmptyValues;47import org.mockito.internal.stubbing.answers.ReturnsMocks;48import org.mockito.internal.stubbing.answers.ThrowsException;49import org.mockito.internal.stubbing.answers.ThrowsExceptionClass;50import

Full Screen

Full Screen

answer

Using AI Code Generation

copy

Full Screen

1package org.mockito;2import java.util.*;3import static org.mockito.Mockito.*;4public class 1 {5 public static void main(String[] args) {6 List mockedList = mock(List.class);7 when(mockedList.get(0)).thenReturn("first");8 when(mockedList.get(1)).thenThrow(new RuntimeException());9 System.out.println(mockedList.get(0));10 System.out.println(mockedList.get(1));11 System.out.println(mockedList.get(999));12 }13}14package org.mockito;15import java.util.*;16import static org.mockito.Mockito.*;17public class 2 {18 public static void main(String[] args) {19 List mockedList = mock(List.class);20 when(mockedList.get(0)).thenReturn("first");21 doAnswer(invocation -> {22 Object arg0 = invocation.getArgument(0);23 System.out.println("called with arguments: " + arg0);24 return "called with arguments: " + arg0;25 }).when(mockedList).get(anyInt());26 System.out.println(mockedList.get(0));27 System.out.println(mockedList.get(999));28 System.out.println(mockedList.get(null));29 }30}31 at org.mockito.1.main(1.java:17)

Full Screen

Full Screen

answer

Using AI Code Generation

copy

Full Screen

1import static org.mockito.Mockito.*;2import org.junit.Test;3import org.mockito.Mockito;4public class TestMockito {5 public void test() {6 MyClass test = Mockito.mock(MyClass.class);7 when(test.getUniqueId()).thenReturn(43);8 test.testing(12);9 verify(test).testing(12);10 verify(test, times(2)).testing(12);11 verify(test, never()).testing(5);12 verify(test, atLeastOnce()).testing(5);13 verify(test, atLeast(2)).testing(5);14 verify(test, times(5)).testing(5);15 verify(test, atMost(3)).testing(5);16 }17}18import static org.mockito.Mockito.*;19import org.junit.Test;20import org.mockito.Mockito;21public class TestMockito {22 public void test() {23 MyClass test = Mockito.mock(MyClass.class);24 when(test.getUniqueId()).thenReturn(43);25 test.testing(12);26 verify(test).testing(12);27 verify(test, times(2)).testing(12);28 verify(test, never()).testing(5);29 verify(test, atLeastOnce()).testing(5);30 verify(test, atLeast(2)).testing(5);31 verify(test, times(5)).testing(5);32 verify(test, atMost(3)).testing(5);33 }34}

Full Screen

Full Screen

answer

Using AI Code Generation

copy

Full Screen

1import static org.mockito.Mockito.*;2import org.mockito.stubbing.*;3import java.util.*;4import org.mockito.invocation.*;5import org.mockito.stubbing.*;6import java.util.*;7import org.mockito.*;8import org.mockito.exceptions.*;9import org.mockito.exceptions.base.*;10import org.mockito.exceptions.verification.*;11import org.mockito.exceptions.verification.junit.*;12import org.mockito.exceptions.verification.junit.ArgumentsAreDifferent;13import org.mockito.exceptions.verification.junit.NeverWantedButInvoked;14import org.mockito.exceptions.verification.junit.NoInteractionsWanted;15import org.mockito.exceptions.verification.junit.TooLittleActualInvocations;16import org.mockito.exceptions.verification.junit.TooManyActualInvocations;17import org.mockito.exceptions.verification.junit.WantedButNotInvoked;18import org.mockito.exceptions.verification.junit.WantedButNotInvokedInOrder;19import org.mockito.exceptions.verification.junit.WantedButNotRetrieved;20import org.mockito.exceptions.verification.junit.WantedButNotRetrievedInOrder;21import org.mockito.exceptions.verification.junit.WantedAtMostX;22import org.mockito.exceptions.verification.junit.WantedAtMostXButInvoked;23import org.mockito.exceptions.verification.junit.WantedAtLeastX;24import org.mockito.exceptions.verification.junit.WantedAtLeastXButNeverInvoked;25import org.mockito.exceptions.verification.junit.WantedAtLeastOnceButNeverInvoked;26import org.mockito.exceptions.verification.junit.WantedAtLeastOnceButNotInvoked;27import org.mockito.exceptions.verification.junit.WantedAtLeastOnceButNotInvokedInOrder;28import org.mockito.exceptions.verification.junit.WantedAtLeastOnceButNotRetrieved;29import org.mockito.exceptions.verification.junit.WantedAtLeastOnceButNotRetrievedInOrder;30import org.mockito.exceptions.verification.junit.WantedButNotInvokedInOrder;31import org.mockito.exceptions.verification.junit.WantedButNotRetrievedInOrder;32import org.mockito.exceptions.verification.junit.ArgumentsAreDifferent;33import org.mockito.exceptions.verification.junit.NeverWantedButInvoked;34import org.mockito.exceptions.verification.junit.NoInteractionsWanted;35import org.mockito.exceptions.verification.junit.TooLittleActualInvocations;36import org.mockito.exceptions.verification.junit.TooManyActualInvocations;37import org.mockito.exceptions.verification.junit.WantedButNotInvoked;38import org.mockito.exceptions.verification.junit.WantedButNotRetrieved;39import org.mockito.exceptions.verification.junit.WantedAtMostX;40import org.mockito.exceptions.verification.junit.WantedAtMostXButInvoked;41import org.mockito.exceptions.verification.junit

Full Screen

Full Screen

answer

Using AI Code Generation

copy

Full Screen

1import org.mockito.Mockito;2public class 1 {3 public static void main(String[] args) {4 List mockedList = Mockito.mock(List.class);5 Mockito.when(mockedList.get(0)).thenAnswer(invocationOnMock -> {6 System.out.println("Called with arguments: " + invocationOnMock.getArguments());7 return "foo";8 });9 System.out.println(mockedList.get(0));10 }11}12import org.mockito.Mockito;13public class 2 {14 public static void main(String[] args) {15 List mockedList = Mockito.mock(List.class);16 Mockito.when(mockedList.get(0)).thenAnswer(invocationOnMock -> {17 System.out.println("Called with arguments: " + invocationOnMock.getArguments());18 return "foo";19 });20 System.out.println(mockedList.get(0));21 }22}23import org.mockito.Mockito;24public class 3 {25 public static void main(String[] args) {26 List mockedList = Mockito.mock(List.class);27 Mockito.when(mockedList.get(0)).thenAnswer(invocationOnMock -> {28 System.out.println("Called with arguments: " + invocationOnMock.getArguments());29 return "foo";30 });31 System.out.println(mockedList.get(0));32 }33}34import org.mockito.Mockito;35public class 4 {36 public static void main(String[] args) {

Full Screen

Full Screen

answer

Using AI Code Generation

copy

Full Screen

1import org.mockito.Mockito;2import org.mockito.ArgumentCaptor;3import org.mockito.Matchers;4import org.mockito.exceptions.verification.junit.ArgumentsAreDifferent;5import org.junit.Before;6import org.junit.Test;7import static org.junit.Assert.*;8import static org.mockito.Mockito.*;9public class JUnitTest {10 private final String expected = "expected";11 private String actual = null;12 private final String argument = "argument";13 private final String argument2 = "argument2";14 private final String argument3 = "argument3";15 private final String argument4 = "argument4";16 private final String argument5 = "argument5";17 private final String argument6 = "argument6";18 private final String argument7 = "argument7";19 private final String argument8 = "argument8";20 private final String argument9 = "argument9";21 private final String argument10 = "argument10";22 private final String argument11 = "argument11";23 private final String argument12 = "argument12";24 private final String argument13 = "argument13";25 private final String argument14 = "argument14";26 private final String argument15 = "argument15";27 private final String argument16 = "argument16";28 private final String argument17 = "argument17";29 private final String argument18 = "argument18";30 private final String argument19 = "argument19";31 private final String argument20 = "argument20";32 private final String argument21 = "argument21";33 private final String argument22 = "argument22";34 private final String argument23 = "argument23";35 private final String argument24 = "argument24";36 private final String argument25 = "argument25";37 private final String argument26 = "argument26";38 private final String argument27 = "argument27";39 private final String argument28 = "argument28";40 private final String argument29 = "argument29";41 private final String argument30 = "argument30";42 private final String argument31 = "argument31";43 private final String argument32 = "argument32";44 private final String argument33 = "argument33";45 private final String argument34 = "argument34";46 private final String argument35 = "argument35";47 private final String argument36 = "argument36";48 private final String argument37 = "argument37";

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful