Added test for ProgrammingServiceImpl
[bgpcep.git] / programming / impl / src / test / java / org / opendaylight / bgpcep / programming / impl / MockedExecutorWrapper.java
1 /*
2  * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.bgpcep.programming.impl;
9
10 import com.google.common.collect.Lists;
11 import com.google.common.util.concurrent.ListenableFuture;
12 import com.google.common.util.concurrent.ListeningExecutorService;
13 import org.mockito.invocation.InvocationOnMock;
14 import org.mockito.stubbing.Answer;
15
16 import java.util.List;
17 import java.util.concurrent.Callable;
18
19 import static org.junit.Assert.assertEquals;
20 import static org.mockito.Matchers.any;
21 import static org.mockito.Mockito.doAnswer;
22 import static org.mockito.Mockito.doReturn;
23 import static org.mockito.Mockito.mock;
24
25 final class MockedExecutorWrapper {
26
27         private List<Object> submittedTasksToExecutor;
28
29         MockedExecutorWrapper() {
30                 submittedTasksToExecutor = Lists.newArrayList();
31         }
32
33         ListeningExecutorService getMockedExecutor() {
34                 ListeningExecutorService mockedExecutor = mock(ListeningExecutorService.class);
35                 Answer<ListenableFuture<?>> submitAnswer = new Answer<ListenableFuture<?>>() {
36                         @Override
37                         public ListenableFuture<?> answer(InvocationOnMock invocation) throws Throwable {
38                                 Object task = invocation.getArguments()[0];
39                                 submittedTasksToExecutor.add(task);
40
41                                 Object result = null;
42                                 if(task instanceof Runnable) {
43                                         ((Runnable)task).run();
44                                 } else if(task instanceof Callable) {
45                                         result = ((Callable<?>)task).call();
46                                 }
47
48                                 ListenableFuture<?> mockedFuture = mock(ListenableFuture.class);
49                                 doReturn(result).when(mockedFuture).get();
50                                 return mockedFuture;
51                         }
52                 };
53                 doAnswer(submitAnswer).when(mockedExecutor).submit(any(Runnable.class));
54                 doAnswer(submitAnswer).when(mockedExecutor).submit(any(Callable.class));
55                 return mockedExecutor;
56         }
57
58         void assertSubmittedTasksSize(int taskCount) {
59                 assertEquals(taskCount, submittedTasksToExecutor.size());
60         }
61 }