]> git.basschouten.com Git - openhab-addons.git/blob
75c9a696505a266f6aa174fd8146593b59ea4ece
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2020 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
7  * This program and the accompanying materials are made available under the
8  * terms of the Eclipse Public License 2.0 which is available at
9  * http://www.eclipse.org/legal/epl-2.0
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.io.transport.modbus.test;
14
15 import java.util.ArrayList;
16 import java.util.function.LongSupplier;
17
18 import org.mockito.invocation.InvocationOnMock;
19 import org.mockito.stubbing.Answer;
20
21 /**
22  * @author Sami Salonen - Initial contribution
23  *
24  * @param <T>
25  */
26 public class ResultCaptor<T> implements Answer<T> {
27
28     private ArrayList<T> results = new ArrayList<>();
29     private LongSupplier longSupplier;
30
31     public ResultCaptor(LongSupplier longSupplier) {
32         this.longSupplier = longSupplier;
33     }
34
35     public ArrayList<T> getAllReturnValues() {
36         return results;
37     }
38
39     @SuppressWarnings("unchecked")
40     @Override
41     public T answer(InvocationOnMock invocationOnMock) throws Throwable {
42         T result = (T) invocationOnMock.callRealMethod();
43         synchronized (this.results) {
44             results.add(result);
45         }
46         long wait = longSupplier.getAsLong();
47         if (wait > 0) {
48             Thread.sleep(wait);
49         }
50         return result;
51     }
52 }