Merge branch 'stable-2.13'
* stable-2.13:
Replace EasyMock with Mockito
Compile against 2.13.3
Change-Id: Ifa2a67c5d6bf1deec5b3b8c34cd87bd661c8afb4
diff --git a/BUCK b/BUCK
index 09293bd..acdb2af 100644
--- a/BUCK
+++ b/BUCK
@@ -15,6 +15,7 @@
TEST_DEPS = GERRIT_PLUGIN_API + PROVIDED_DEPS + DEPS + [
':evict-cache__plugin',
+ ':mockito',
]
gerrit_plugin(
@@ -58,3 +59,30 @@
license = 'Apache2.0',
attach_source = False,
)
+
+maven_jar(
+ name = 'mockito',
+ id = 'org.mockito:mockito-core:2.5.0',
+ sha1 = 'be28d46a52c7f2563580adeca350145e9ce916f8',
+ license = 'MIT',
+ deps = [
+ ':byte-buddy',
+ ':objenesis',
+ ],
+)
+
+maven_jar(
+ name = 'byte-buddy',
+ id = 'net.bytebuddy:byte-buddy:1.5.12',
+ sha1 = 'b1ba1d15f102b36ed43b826488114678d6d413da',
+ license = 'DO_NOT_DISTRIBUTE',
+ attach_source = False,
+)
+
+maven_jar(
+ name = 'objenesis',
+ id = 'org.objenesis:objenesis:2.4',
+ sha1 = '2916b6c96b50c5b3ec4452ed99401db745aabb27',
+ license = 'DO_NOT_DISTRIBUTE',
+ attach_source = False,
+)
diff --git a/lib/gerrit/BUCK b/lib/gerrit/BUCK
index fe8119e..f6c68a4 100644
--- a/lib/gerrit/BUCK
+++ b/lib/gerrit/BUCK
@@ -1,11 +1,12 @@
include_defs('//bucklets/maven_jar.bucklet')
-VER = '2.13-SNAPSHOT'
-REPO = MAVEN_LOCAL
+VER = '2.13.3'
+REPO = MAVEN_CENTRAL
maven_jar(
name = 'plugin-api',
id = 'com.google.gerrit:gerrit-plugin-api:' + VER,
+ sha1 = '78df190269b0d5a4bc4f61ab3a66a49252b779eb',
license = 'Apache2.0',
attach_source = False,
repository = REPO,
@@ -14,6 +15,7 @@
maven_jar(
name = 'acceptance-framework',
id = 'com.google.gerrit:gerrit-acceptance-framework:' + VER,
+ sha1 = '76eceefa7e31c6945513c36c4d106066d1df3e63',
license = 'Apache2.0',
attach_source = False,
repository = REPO,
diff --git a/src/test/java/com/ericsson/gerrit/plugins/evictcache/CacheResponseHandlerTest.java b/src/test/java/com/ericsson/gerrit/plugins/evictcache/CacheResponseHandlerTest.java
index 1d2dd3e..8e94727 100644
--- a/src/test/java/com/ericsson/gerrit/plugins/evictcache/CacheResponseHandlerTest.java
+++ b/src/test/java/com/ericsson/gerrit/plugins/evictcache/CacheResponseHandlerTest.java
@@ -15,20 +15,20 @@
package com.ericsson.gerrit.plugins.evictcache;
import static com.google.common.truth.Truth.assertThat;
-import static org.easymock.EasyMock.expect;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
import com.ericsson.gerrit.plugins.evictcache.CacheResponseHandler.CacheResult;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.entity.StringEntity;
-import org.easymock.EasyMockSupport;
import org.junit.Before;
import org.junit.Test;
import java.io.UnsupportedEncodingException;
-public class CacheResponseHandlerTest extends EasyMockSupport {
+public class CacheResponseHandlerTest {
private static final int ERROR = 400;
private static final int OK = 204;
private static final String EMPTY_ENTITY = "";
@@ -59,12 +59,11 @@
private HttpResponse setupMocks(int httpCode, String entity)
throws UnsupportedEncodingException {
- StatusLine status = createNiceMock(StatusLine.class);
- expect(status.getStatusCode()).andReturn(httpCode).anyTimes();
- HttpResponse response = createNiceMock(HttpResponse.class);
- expect(response.getStatusLine()).andReturn(status).anyTimes();
- expect(response.getEntity()).andReturn(new StringEntity(entity)).anyTimes();
- replayAll();
+ StatusLine status = mock(StatusLine.class);
+ when(status.getStatusCode()).thenReturn(httpCode);
+ HttpResponse response = mock(HttpResponse.class);
+ when(response.getStatusLine()).thenReturn(status);
+ when(response.getEntity()).thenReturn(new StringEntity(entity));
return response;
}
}
diff --git a/src/test/java/com/ericsson/gerrit/plugins/evictcache/ConfigurationTest.java b/src/test/java/com/ericsson/gerrit/plugins/evictcache/ConfigurationTest.java
index c884291..88ddc54 100644
--- a/src/test/java/com/ericsson/gerrit/plugins/evictcache/ConfigurationTest.java
+++ b/src/test/java/com/ericsson/gerrit/plugins/evictcache/ConfigurationTest.java
@@ -15,41 +15,46 @@
package com.ericsson.gerrit.plugins.evictcache;
import static com.google.common.truth.Truth.assertThat;
-import static org.easymock.EasyMock.expect;
-
-import org.easymock.EasyMockSupport;
-import org.junit.Before;
-import org.junit.Test;
+import static org.mockito.Mockito.when;
import com.google.gerrit.server.config.PluginConfig;
import com.google.gerrit.server.config.PluginConfigFactory;
-public class ConfigurationTest extends EasyMockSupport {
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.junit.MockitoJUnitRunner;
+
+@RunWith(MockitoJUnitRunner.class)
+public class ConfigurationTest {
private static final String PASS = "fakePass";
private static final String USER = "fakeUser";
private static final String URL = "fakeUrl";
private static final String EMPTY = "";
+ private static final boolean CUSTOM_VALUES = true;
+ private static final boolean DEFAULT_VALUES = false;
private static final int TIMEOUT = 5000;
private static final int MAX_TRIES = 5;
private static final int RETRY_INTERVAL = 1000;
private static final int THREAD_POOL_SIZE = 1;
+ @Mock
private PluginConfigFactory cfgFactoryMock;
+ @Mock
private PluginConfig configMock;
private Configuration configuration;
private String pluginName = "evict-cache";
@Before
public void setUp() throws Exception {
- configMock = createNiceMock(PluginConfig.class);
- cfgFactoryMock = createMock(PluginConfigFactory.class);
- expect(cfgFactoryMock.getFromGerritConfig(pluginName, true))
- .andStubReturn(configMock);
+ when(cfgFactoryMock.getFromGerritConfig(pluginName, true))
+ .thenReturn(configMock);
}
@Test
public void testValuesPresentInGerritConfig() throws Exception {
- buildMocks(true);
+ buildMocks(CUSTOM_VALUES);
assertThat(configuration.getUrl()).isEqualTo(URL);
assertThat(configuration.getUser()).isEqualTo(USER);
assertThat(configuration.getPassword()).isEqualTo(PASS);
@@ -62,7 +67,7 @@
@Test
public void testValuesNotPresentInGerritConfig() throws Exception {
- buildMocks(false);
+ buildMocks(DEFAULT_VALUES);
assertThat(configuration.getUrl()).isEqualTo(EMPTY);
assertThat(configuration.getUser()).isEqualTo(EMPTY);
assertThat(configuration.getPassword()).isEqualTo(EMPTY);
@@ -75,28 +80,28 @@
@Test
public void testUrlTrailingSlashIsDropped() throws Exception {
- expect(configMock.getString("url")).andReturn(URL + "/");
- replayAll();
+ when(configMock.getString("url")).thenReturn(URL + "/");
+
configuration = new Configuration(cfgFactoryMock, pluginName);
assertThat(configuration).isNotNull();
assertThat(configuration.getUrl()).isEqualTo(URL);
}
private void buildMocks(boolean values) {
- expect(configMock.getString("url")).andReturn(values ? URL : null);
- expect(configMock.getString("user")).andReturn(values ? USER : null);
- expect(configMock.getString("password")).andReturn(values ? PASS : null);
- expect(configMock.getInt("connectionTimeout", TIMEOUT))
- .andReturn(values ? TIMEOUT : 0);
- expect(configMock.getInt("socketTimeout", TIMEOUT))
- .andReturn(values ? TIMEOUT : 0);
- expect(configMock.getInt("maxTries", MAX_TRIES))
- .andReturn(values ? MAX_TRIES : 0);
- expect(configMock.getInt("retryInterval", RETRY_INTERVAL))
- .andReturn(values ? RETRY_INTERVAL : 0);
- expect(configMock.getInt("threadPoolSize", THREAD_POOL_SIZE))
- .andReturn(values ? THREAD_POOL_SIZE : 0);
- replayAll();
+ when(configMock.getString("url")).thenReturn(values ? URL : null);
+ when(configMock.getString("user")).thenReturn(values ? USER : null);
+ when(configMock.getString("password")).thenReturn(values ? PASS : null);
+ when(configMock.getInt("connectionTimeout", TIMEOUT))
+ .thenReturn(values ? TIMEOUT : 0);
+ when(configMock.getInt("socketTimeout", TIMEOUT))
+ .thenReturn(values ? TIMEOUT : 0);
+ when(configMock.getInt("maxTries", MAX_TRIES))
+ .thenReturn(values ? MAX_TRIES : 0);
+ when(configMock.getInt("retryInterval", RETRY_INTERVAL))
+ .thenReturn(values ? RETRY_INTERVAL : 0);
+ when(configMock.getInt("threadPoolSize", THREAD_POOL_SIZE))
+ .thenReturn(values ? THREAD_POOL_SIZE : 0);
+
configuration = new Configuration(cfgFactoryMock, pluginName);
}
}
diff --git a/src/test/java/com/ericsson/gerrit/plugins/evictcache/ContextTest.java b/src/test/java/com/ericsson/gerrit/plugins/evictcache/ContextTest.java
index 06c54ed..f7f51b6 100644
--- a/src/test/java/com/ericsson/gerrit/plugins/evictcache/ContextTest.java
+++ b/src/test/java/com/ericsson/gerrit/plugins/evictcache/ContextTest.java
@@ -16,10 +16,9 @@
import static com.google.common.truth.Truth.assertThat;
-import org.easymock.EasyMockSupport;
import org.junit.Test;
-public class ContextTest extends EasyMockSupport {
+public class ContextTest {
@Test
public void testInitialValueNotNull() throws Exception {
diff --git a/src/test/java/com/ericsson/gerrit/plugins/evictcache/EvictCacheExecutorProviderTest.java b/src/test/java/com/ericsson/gerrit/plugins/evictcache/EvictCacheExecutorProviderTest.java
index 90193bb..a01b187 100644
--- a/src/test/java/com/ericsson/gerrit/plugins/evictcache/EvictCacheExecutorProviderTest.java
+++ b/src/test/java/com/ericsson/gerrit/plugins/evictcache/EvictCacheExecutorProviderTest.java
@@ -15,34 +15,36 @@
package com.ericsson.gerrit.plugins.evictcache;
import static com.google.common.truth.Truth.assertThat;
-import static org.easymock.EasyMock.expect;
-import static org.easymock.EasyMock.expectLastCall;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
-import com.google.gerrit.extensions.annotations.PluginName;
import com.google.gerrit.server.git.WorkQueue;
-import org.easymock.EasyMockSupport;
import org.junit.Before;
import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.junit.MockitoJUnitRunner;
-public class EvictCacheExecutorProviderTest extends EasyMockSupport {
+@RunWith(MockitoJUnitRunner.class)
+public class EvictCacheExecutorProviderTest {
+ private static final String PLUGIN_NAME = "evict-cache";
+
+ @Mock
private WorkQueue.Executor executorMock;
private EvictCacheExecutorProvider evictCacheExecutorProvider;
- @PluginName String pluginName;
-
@Before
public void setUp() throws Exception {
- executorMock = createStrictMock(WorkQueue.Executor.class);
- WorkQueue workQueueMock = createNiceMock(WorkQueue.class);
- expect(workQueueMock.createQueue(4,
- "Evict cache [" + pluginName + " plugin]"))
- .andReturn(executorMock);
- Configuration configMock = createStrictMock(Configuration.class);
- expect(configMock.getThreadPoolSize()).andReturn(4);
- replayAll();
+ WorkQueue workQueueMock = mock(WorkQueue.class);
+ when(workQueueMock.createQueue(4,
+ "Evict cache [" + PLUGIN_NAME + " plugin]")).thenReturn(executorMock);
+ Configuration configMock = mock(Configuration.class);
+ when(configMock.getThreadPoolSize()).thenReturn(4);
+
evictCacheExecutorProvider =
- new EvictCacheExecutorProvider(workQueueMock, pluginName, configMock);
+ new EvictCacheExecutorProvider(workQueueMock, PLUGIN_NAME, configMock);
}
@Test
@@ -52,17 +54,11 @@
@Test
public void testStop() throws Exception {
- resetAll();
- executorMock.shutdown();
- expectLastCall().once();
- executorMock.unregisterWorkQueue();
- expectLastCall().once();
- replayAll();
-
evictCacheExecutorProvider.start();
assertThat(evictCacheExecutorProvider.get()).isEqualTo(executorMock);
evictCacheExecutorProvider.stop();
- verifyAll();
+ verify(executorMock).shutdown();
+ verify(executorMock).unregisterWorkQueue();
assertThat(evictCacheExecutorProvider.get()).isNull();
}
}
diff --git a/src/test/java/com/ericsson/gerrit/plugins/evictcache/EvictCacheHandlerTest.java b/src/test/java/com/ericsson/gerrit/plugins/evictcache/EvictCacheHandlerTest.java
deleted file mode 100644
index 93002ab..0000000
--- a/src/test/java/com/ericsson/gerrit/plugins/evictcache/EvictCacheHandlerTest.java
+++ /dev/null
@@ -1,140 +0,0 @@
-// Copyright (C) 2015 Ericsson
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package com.ericsson.gerrit.plugins.evictcache;
-
-import static org.easymock.EasyMock.expect;
-
-import com.google.common.cache.RemovalNotification;
-
-import org.easymock.EasyMock;
-import org.easymock.EasyMockSupport;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.powermock.api.easymock.PowerMock;
-import org.powermock.core.classloader.annotations.PrepareForTest;
-import org.powermock.modules.junit4.PowerMockRunner;
-
-import java.util.concurrent.ScheduledThreadPoolExecutor;
-
-@RunWith(PowerMockRunner.class)
-@PrepareForTest(RemovalNotification.class)
-public class EvictCacheHandlerTest extends EasyMockSupport {
- private static final String pluginName = "evict-cache";
- private static final String cacheName = "project_list";
- private static final String invalidCacheName = "INVALID";
- private static final boolean MOCK_REST_CLIENT = true;
- private static final boolean DO_NOT_MOCK_REST_CLIENT = false;
- private static final boolean WAS_EVICTED = true;
- private static final boolean WAS_NOT_EVICTED = false;
-
- private EvictCacheHandler<Object, Object> evictCacheHandler;
- private RemovalNotification<Object, Object> notification;
- private ScheduledThreadPoolExecutor pool;
- private RestSession restClient;
-
- @Test
- public void testEvictCacheHandler() {
- setUpMocks(MOCK_REST_CLIENT, WAS_NOT_EVICTED);
- EasyMock.replay(restClient);
- evictCacheHandler.onRemoval(pluginName, cacheName, notification);
- verifyAll();
- }
-
- @Test
- public void testInvalidCacheName() {
- setUpMocks(DO_NOT_MOCK_REST_CLIENT, WAS_NOT_EVICTED);
- replayAll();
- evictCacheHandler.onRemoval(pluginName, invalidCacheName, notification);
- verifyAll();
- }
-
- @Test
- public void testInvalidRemovalCause() {
- setUpMocks(DO_NOT_MOCK_REST_CLIENT, WAS_EVICTED);
- evictCacheHandler.onRemoval(pluginName, cacheName, notification);
- verifyAll();
- }
-
- @Test
- public void testInvalidRemovalCauseAndCacheName() {
- setUpMocks(DO_NOT_MOCK_REST_CLIENT, WAS_EVICTED);
- evictCacheHandler.onRemoval(pluginName, invalidCacheName, notification);
- verifyAll();
- }
-
- @Test
- public void testForwardedInvalidRemovalCauseAndCacheName() {
- setUpMocks(DO_NOT_MOCK_REST_CLIENT, WAS_EVICTED);
- Context.setForwardedEvent();
- try {
- evictCacheHandler.onRemoval(pluginName, invalidCacheName, notification);
- } finally {
- Context.unsetForwardedEvent();
- }
- verifyAll();
- }
-
- @Test
- public void testEvictCacheHandlerIsForwarded() {
- setUpMocks(DO_NOT_MOCK_REST_CLIENT, WAS_NOT_EVICTED);
- Context.setForwardedEvent();
- try {
- evictCacheHandler.onRemoval(pluginName, cacheName, notification);
- } finally {
- Context.unsetForwardedEvent();
- }
- verifyAll();
- }
-
- @Test
- public void testEvictCacheIsForwardedAndAlreadyEvicted() {
- setUpMocks(DO_NOT_MOCK_REST_CLIENT, WAS_EVICTED);
- Context.setForwardedEvent();
- try {
- evictCacheHandler.onRemoval(pluginName, cacheName, notification);
- } finally {
- Context.unsetForwardedEvent();
- }
- verifyAll();
- }
-
- @SuppressWarnings({"rawtypes", "unchecked"})
- private void setUpMocks(boolean mockRestClient, boolean wasEvicted) {
- notification = PowerMock.createMock(RemovalNotification.class);
- pool = new PoolMock(1);
- Object key = new Object();
- if (mockRestClient) {
- restClient = createMock(RestSession.class);
- expect(restClient.evict(pluginName, cacheName, key)).andReturn(true);
- } else {
- restClient = null;
- }
- expect(notification.wasEvicted()).andReturn(wasEvicted);
- expect(notification.getKey()).andReturn(key);
- EasyMock.replay(notification);
- evictCacheHandler = new EvictCacheHandler(restClient, pool);
- }
-
- private class PoolMock extends ScheduledThreadPoolExecutor {
- PoolMock(int corePoolSize) {
- super(corePoolSize);
- }
-
- @Override
- public void execute(Runnable command) {
- command.run();
- }
- }
-}
diff --git a/src/test/java/com/ericsson/gerrit/plugins/evictcache/EvictCacheIT.java b/src/test/java/com/ericsson/gerrit/plugins/evictcache/EvictCacheIT.java
index db900c5..b44ac31 100644
--- a/src/test/java/com/ericsson/gerrit/plugins/evictcache/EvictCacheIT.java
+++ b/src/test/java/com/ericsson/gerrit/plugins/evictcache/EvictCacheIT.java
@@ -21,9 +21,10 @@
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static com.github.tomakehurst.wiremock.client.WireMock.verify;
+import com.google.gerrit.acceptance.GerritConfig;
+import com.google.gerrit.acceptance.GerritConfigs;
import com.google.gerrit.acceptance.NoHttpd;
import com.google.gerrit.acceptance.PluginDaemonTest;
-import com.google.gerrit.server.config.SitePaths;
import com.github.tomakehurst.wiremock.http.Request;
import com.github.tomakehurst.wiremock.http.RequestListener;
@@ -31,36 +32,25 @@
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import org.apache.http.HttpStatus;
-import org.eclipse.jgit.storage.file.FileBasedConfig;
-import org.eclipse.jgit.util.FS;
import org.junit.Rule;
import org.junit.Test;
-import org.junit.runner.Description;
-import java.io.IOException;
-import java.nio.file.Files;
-import java.nio.file.Path;
import java.util.concurrent.TimeUnit;
@NoHttpd
public class EvictCacheIT extends PluginDaemonTest {
- private static final String PLUGIN_NAME = "evict-cache";
-
@Rule
public WireMockRule wireMockRule = new WireMockRule(Constants.PORT);
- @Override
- protected void beforeTest(Description description)
- throws Exception {
- setConfig("url", Constants.URL);
- setConfig("user", "admin");
- super.beforeTest(description);
- }
-
@Test
+ @GerritConfigs({
+ @GerritConfig(name = "plugin.evict-cache.url", value = Constants.URL),
+ @GerritConfig(name = "plugin.evict-cache.user", value = "admin")
+ })
public void flushAndSendPost() throws Exception {
- final String flushRequest = Constants.ENDPOINT_BASE + Constants.PROJECT_LIST;
+ final String flushRequest =
+ Constants.ENDPOINT_BASE + Constants.PROJECT_LIST;
wireMockRule.addMockServiceRequestListener(new RequestListener() {
@Override
public void requestReceived(Request request, Response response) {
@@ -74,29 +64,11 @@
givenThat(post(urlEqualTo(flushRequest))
.willReturn(aResponse().withStatus(HttpStatus.SC_OK)));
- adminSshSession.exec("gerrit flush-caches --cache " + Constants.PROJECT_LIST);
+ adminSshSession
+ .exec("gerrit flush-caches --cache " + Constants.PROJECT_LIST);
synchronized (flushRequest) {
flushRequest.wait(TimeUnit.SECONDS.toMillis(2));
}
verify(postRequestedFor(urlEqualTo(flushRequest)));
}
-
- private void setConfig(String name, String value) throws Exception {
- SitePaths sitePath = new SitePaths(tempSiteDir.getRoot().toPath());
- FileBasedConfig cfg = getGerritConfigFile(sitePath);
- cfg.load();
- cfg.setString("plugin", PLUGIN_NAME, name, value);
- cfg.save();
- }
-
- private FileBasedConfig getGerritConfigFile(SitePaths sitePath)
- throws IOException {
- FileBasedConfig cfg =
- new FileBasedConfig(sitePath.gerrit_config.toFile(), FS.DETECTED);
- if (!cfg.getFile().exists()) {
- Path etc_path = Files.createDirectories(sitePath.etc_dir);
- Files.createFile(etc_path.resolve("gerrit.config"));
- }
- return cfg;
- }
}
diff --git a/src/test/java/com/ericsson/gerrit/plugins/evictcache/EvictCacheRestApiServletTest.java b/src/test/java/com/ericsson/gerrit/plugins/evictcache/EvictCacheRestApiServletTest.java
index 9c85978..3db1f75 100644
--- a/src/test/java/com/ericsson/gerrit/plugins/evictcache/EvictCacheRestApiServletTest.java
+++ b/src/test/java/com/ericsson/gerrit/plugins/evictcache/EvictCacheRestApiServletTest.java
@@ -16,126 +16,116 @@
import static javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST;
import static javax.servlet.http.HttpServletResponse.SC_NO_CONTENT;
-import static org.easymock.EasyMock.expect;
-import static org.easymock.EasyMock.expectLastCall;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
import com.google.common.cache.Cache;
import com.google.gerrit.extensions.registration.DynamicMap;
-import org.easymock.EasyMockSupport;
import org.junit.Before;
import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.junit.MockitoJUnitRunner;
import java.io.BufferedReader;
import java.io.IOException;
-import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
-public class EvictCacheRestApiServletTest extends EasyMockSupport {
- private static final String PLUGIN_NAME = "gerrit";
+@RunWith(MockitoJUnitRunner.class)
+public class EvictCacheRestApiServletTest {
+ @Mock
private HttpServletRequest request;
+ @Mock
private HttpServletResponse response;
+ @Mock
private BufferedReader reader;
- private EvictCacheRestApiServlet servlet;
+ @Mock
private DynamicMap<Cache<?, ?>> cacheMap;
- @SuppressWarnings("rawtypes")
- private Cache cache;
+ private EvictCacheRestApiServlet servlet;
+
+ @Before
+ public void setUp() {
+ servlet = new EvictCacheRestApiServlet(cacheMap);
+ }
@Test
- public void evictAccounts() throws IOException, ServletException {
+ public void evictAccounts() throws Exception {
configureMocksFor(Constants.ACCOUNTS);
- servlet.doPost(request, response);
- verifyAll();
+ verifyResponseIsOK();
}
@Test
- public void evictProjectList() throws IOException, ServletException {
+ public void evictProjectList() throws Exception {
configureMocksFor(Constants.PROJECT_LIST);
- servlet.doPost(request, response);
- verifyAll();
+ verifyResponseIsOK();
}
@Test
- public void evictGroups() throws IOException, ServletException {
+ public void evictGroups() throws Exception {
configureMocksFor(Constants.GROUPS);
- servlet.doPost(request, response);
- verifyAll();
+ verifyResponseIsOK();
}
@Test
- public void evictGroupsByInclude() throws IOException, ServletException {
+ public void evictGroupsByInclude() throws Exception {
configureMocksFor(Constants.GROUPS_BYINCLUDE);
- servlet.doPost(request, response);
- verifyAll();
+ verifyResponseIsOK();
}
@Test
- public void evictGroupsMembers() throws IOException, ServletException {
+ public void evictGroupsMembers() throws Exception {
configureMocksFor(Constants.GROUPS_MEMBERS);
servlet.doPost(request, response);
- verifyAll();
+
}
@Test
- public void evictDefault() throws IOException, ServletException {
+ public void evictDefault() throws Exception {
configureMocksFor(Constants.DEFAULT);
+ verifyResponseIsOK();
+ }
+
+ private void verifyResponseIsOK() throws Exception {
servlet.doPost(request, response);
- verifyAll();
+ verify(response).setStatus(SC_NO_CONTENT);
}
@Test
- public void badRequest() throws IOException, ServletException {
- expect(request.getPathInfo()).andReturn("/someCache");
+ public void badRequest() throws Exception {
+ when(request.getPathInfo()).thenReturn("/someCache");
String errorMessage = "someError";
- expect(request.getReader()).andThrow(new IOException(errorMessage));
- response.sendError(SC_BAD_REQUEST, errorMessage);
- expectLastCall().once();
- replayAll();
+ doThrow(new IOException(errorMessage)).when(request).getReader();
servlet.doPost(request, response);
- verifyAll();
+ verify(response).sendError(SC_BAD_REQUEST, errorMessage);
}
@Test
public void errorWhileSendingErrorMessage() throws Exception {
- expect(request.getPathInfo()).andReturn("/someCache");
+ when(request.getPathInfo()).thenReturn("/someCache");
String errorMessage = "someError";
- expect(request.getReader()).andThrow(new IOException(errorMessage));
- response.sendError(SC_BAD_REQUEST, errorMessage);
- expectLastCall().andThrow(new IOException("someOtherError"));
- replayAll();
+ doThrow(new IOException(errorMessage)).when(request).getReader();
servlet.doPost(request, response);
- verifyAll();
- }
-
- @Before
- @SuppressWarnings("unchecked")
- public void setUp() {
- cacheMap = createMock(DynamicMap.class);
- request = createMock(HttpServletRequest.class);
- reader = createMock(BufferedReader.class);
- response = createNiceMock(HttpServletResponse.class);
- cache = createNiceMock(Cache.class);
- servlet = new EvictCacheRestApiServlet(cacheMap);
+ verify(response).sendError(SC_BAD_REQUEST, errorMessage);
}
@SuppressWarnings("unchecked")
private void configureMocksFor(String cacheName) throws IOException {
- expect(cacheMap.get(PLUGIN_NAME, cacheName)).andReturn(cache);
- expect(request.getPathInfo()).andReturn("/" + cacheName);
- expect(request.getReader()).andReturn(reader);
+ when(cacheMap.get("gerrit", cacheName)).thenReturn(mock(Cache.class));
+ when(request.getPathInfo()).thenReturn("/" + cacheName);
+ when(request.getReader()).thenReturn(reader);
if (Constants.DEFAULT.equals(cacheName)) {
- expect(reader.readLine()).andReturn("abc");
+ when(reader.readLine()).thenReturn("abc");
} else if (Constants.GROUPS_BYINCLUDE.equals(cacheName)
|| Constants.GROUPS_MEMBERS.equals(cacheName)) {
- expect(reader.readLine()).andReturn("{\"uuid\":\"abcd1234\"}");
+ when(reader.readLine()).thenReturn("{\"uuid\":\"abcd1234\"}");
} else {
- expect(reader.readLine()).andReturn("{}");
+ when(reader.readLine()).thenReturn("{}");
}
- response.setStatus(SC_NO_CONTENT);
- expectLastCall().once();
- replayAll();
}
}
diff --git a/src/test/java/com/ericsson/gerrit/plugins/evictcache/HttpClientProviderTest.java b/src/test/java/com/ericsson/gerrit/plugins/evictcache/HttpClientProviderTest.java
index eb6cbf5..e64cf7c 100644
--- a/src/test/java/com/ericsson/gerrit/plugins/evictcache/HttpClientProviderTest.java
+++ b/src/test/java/com/ericsson/gerrit/plugins/evictcache/HttpClientProviderTest.java
@@ -15,7 +15,7 @@
package com.ericsson.gerrit.plugins.evictcache;
import static com.google.common.truth.Truth.assertThat;
-import static org.easymock.EasyMock.expect;
+import static org.mockito.Mockito.when;
import com.google.gerrit.lifecycle.LifecycleModule;
import com.google.inject.Guice;
@@ -23,27 +23,27 @@
import com.google.inject.Scopes;
import org.apache.http.impl.client.CloseableHttpClient;
-import org.easymock.EasyMockSupport;
import org.junit.Before;
import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.junit.MockitoJUnitRunner;
-public class HttpClientProviderTest extends EasyMockSupport {
+@RunWith(MockitoJUnitRunner.class)
+public class HttpClientProviderTest {
private static final int TIME_INTERVAL = 1000;
private static final String EMPTY = "";
+ @Mock
private Configuration config;
@Before
public void setUp() throws Exception {
- config = createNiceMock(Configuration.class);
- expect(config.getUrl()).andReturn(EMPTY).anyTimes();
- expect(config.getUser()).andReturn(EMPTY).anyTimes();
- expect(config.getPassword()).andReturn(EMPTY).anyTimes();
- expect(config.getMaxTries()).andReturn(1).anyTimes();
- expect(config.getConnectionTimeout()).andReturn(TIME_INTERVAL).anyTimes();
- expect(config.getSocketTimeout()).andReturn(TIME_INTERVAL).anyTimes();
- expect(config.getRetryInterval()).andReturn(TIME_INTERVAL).anyTimes();
- replayAll();
+ when(config.getUrl()).thenReturn(EMPTY);
+ when(config.getUser()).thenReturn(EMPTY);
+ when(config.getPassword()).thenReturn(EMPTY);
+ when(config.getConnectionTimeout()).thenReturn(TIME_INTERVAL);
+ when(config.getSocketTimeout()).thenReturn(TIME_INTERVAL);
}
@Test
diff --git a/src/test/java/com/ericsson/gerrit/plugins/evictcache/HttpSessionTest.java b/src/test/java/com/ericsson/gerrit/plugins/evictcache/HttpSessionTest.java
index d11e648..f45e52d 100644
--- a/src/test/java/com/ericsson/gerrit/plugins/evictcache/HttpSessionTest.java
+++ b/src/test/java/com/ericsson/gerrit/plugins/evictcache/HttpSessionTest.java
@@ -19,22 +19,21 @@
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static com.google.common.truth.Truth.assertThat;
-import static org.easymock.EasyMock.expect;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
import com.ericsson.gerrit.plugins.evictcache.CacheResponseHandler.CacheResult;
import com.github.tomakehurst.wiremock.http.Fault;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import com.github.tomakehurst.wiremock.stubbing.Scenario;
-import org.apache.http.impl.client.CloseableHttpClient;
-import org.easymock.EasyMockSupport;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import java.net.SocketTimeoutException;
-public class HttpSessionTest extends EasyMockSupport {
+public class HttpSessionTest {
private static final int MAX_TRIES = 3;
private static final int RETRY_INTERVAL = 250;
private static final int TIMEOUT = 500;
@@ -52,8 +51,6 @@
private static final String RETRY_AT_ERROR = "Retry at error";
private static final String RETRY_AT_DELAY = "Retry at delay";
- private Configuration cfg;
- private CloseableHttpClient httpClient;
private HttpSession httpSession;
@Rule
@@ -61,17 +58,17 @@
@Before
public void setUp() throws Exception {
- cfg = createMock(Configuration.class);
- expect(cfg.getUrl()).andReturn(Constants.URL).anyTimes();
- expect(cfg.getUser()).andReturn("user");
- expect(cfg.getPassword()).andReturn("pass");
- expect(cfg.getMaxTries()).andReturn(MAX_TRIES).anyTimes();
- expect(cfg.getConnectionTimeout()).andReturn(TIMEOUT).anyTimes();
- expect(cfg.getSocketTimeout()).andReturn(TIMEOUT).anyTimes();
- expect(cfg.getRetryInterval()).andReturn(RETRY_INTERVAL).anyTimes();
- replayAll();
- httpClient = new HttpClientProvider(cfg).get();
- httpSession = new HttpSession(httpClient, Constants.URL);
+ Configuration cfg = mock(Configuration.class);
+ when(cfg.getUrl()).thenReturn(Constants.URL);
+ when(cfg.getUser()).thenReturn("user");
+ when(cfg.getPassword()).thenReturn("pass");
+ when(cfg.getMaxTries()).thenReturn(MAX_TRIES);
+ when(cfg.getConnectionTimeout()).thenReturn(TIMEOUT);
+ when(cfg.getSocketTimeout()).thenReturn(TIMEOUT);
+ when(cfg.getRetryInterval()).thenReturn(RETRY_INTERVAL);
+
+ httpSession =
+ new HttpSession(new HttpClientProvider(cfg).get(), Constants.URL);
}
@Test
diff --git a/src/test/java/com/ericsson/gerrit/plugins/evictcache/ModuleTest.java b/src/test/java/com/ericsson/gerrit/plugins/evictcache/ModuleTest.java
index 3262101..479ed90 100644
--- a/src/test/java/com/ericsson/gerrit/plugins/evictcache/ModuleTest.java
+++ b/src/test/java/com/ericsson/gerrit/plugins/evictcache/ModuleTest.java
@@ -15,19 +15,19 @@
package com.ericsson.gerrit.plugins.evictcache;
import static com.google.common.truth.Truth.assertThat;
-import static org.easymock.EasyMock.expect;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
-import org.easymock.EasyMockSupport;
import org.junit.Test;
-public class ModuleTest extends EasyMockSupport {
+public class ModuleTest {
@Test
public void testSyncUrlProvider() {
- Configuration configMock = createNiceMock(Configuration.class);
+ Configuration configMock = mock(Configuration.class);
String expected = "someUrl";
- expect(configMock.getUrl()).andReturn(expected);
- replayAll();
+ when(configMock.getUrl()).thenReturn(expected);
+
Module module = new Module();
assertThat(module.syncUrl(configMock)).isEqualTo(expected);
}
diff --git a/src/test/java/com/ericsson/gerrit/plugins/evictcache/RestSessionTest.java b/src/test/java/com/ericsson/gerrit/plugins/evictcache/RestSessionTest.java
index 0801dfa..731792b 100644
--- a/src/test/java/com/ericsson/gerrit/plugins/evictcache/RestSessionTest.java
+++ b/src/test/java/com/ericsson/gerrit/plugins/evictcache/RestSessionTest.java
@@ -15,7 +15,9 @@
package com.ericsson.gerrit.plugins.evictcache;
import static com.google.common.truth.Truth.assertThat;
-import static org.easymock.EasyMock.expect;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
import com.google.common.base.Joiner;
import com.google.gerrit.reviewdb.client.Account;
@@ -23,59 +25,68 @@
import com.ericsson.gerrit.plugins.evictcache.CacheResponseHandler.CacheResult;
-import org.easymock.EasyMockSupport;
import org.junit.Test;
import java.io.IOException;
-public class RestSessionTest extends EasyMockSupport {
+public class RestSessionTest {
private static final String EVICT = "evict";
private static final String SOURCE_NAME = "gerrit";
private static final String PLUGIN_NAME = "evict-cache";
private static final String EMPTY_JSON = "{}";
private static final String EMPTY_JSON2 = "\"{}\"";
private static final String ID_RESPONSE = "{\"id\":0}";
+ private static final boolean OK_RESPONSE = true;
+ private static final boolean FAIL_RESPONSE = false;
+ private static final boolean THROW_EXCEPTION = true;
+ private static final boolean DO_NOT_THROW_EXCEPTION = false;
private RestSession restClient;
@Test
public void testEvictCacheOK() throws Exception {
- setupMocks(Constants.DEFAULT, EMPTY_JSON2, true, false);
+ setupMocks(Constants.DEFAULT, EMPTY_JSON2, OK_RESPONSE,
+ DO_NOT_THROW_EXCEPTION);
assertThat(restClient.evict(SOURCE_NAME, Constants.DEFAULT, EMPTY_JSON))
.isTrue();
}
@Test
public void testEvictAccountsOK() throws Exception {
- setupMocks(Constants.ACCOUNTS, ID_RESPONSE, true, false);
+ setupMocks(Constants.ACCOUNTS, ID_RESPONSE, OK_RESPONSE,
+ DO_NOT_THROW_EXCEPTION);
assertThat(restClient.evict(SOURCE_NAME, Constants.ACCOUNTS,
- createMock(Account.Id.class))).isTrue();
+ mock(Account.Id.class))).isTrue();
}
@Test
public void testEvictGroupsOK() throws Exception {
- setupMocks(Constants.GROUPS, ID_RESPONSE, true, false);
+ setupMocks(Constants.GROUPS, ID_RESPONSE, OK_RESPONSE,
+ DO_NOT_THROW_EXCEPTION);
assertThat(restClient.evict(SOURCE_NAME, Constants.GROUPS,
- createMock(AccountGroup.Id.class))).isTrue();
+ mock(AccountGroup.Id.class))).isTrue();
}
@Test
public void testEvictGroupsByIncludeOK() throws Exception {
- setupMocks(Constants.GROUPS_BYINCLUDE, EMPTY_JSON, true, false);
+ setupMocks(Constants.GROUPS_BYINCLUDE, EMPTY_JSON, OK_RESPONSE,
+ DO_NOT_THROW_EXCEPTION);
assertThat(restClient.evict(SOURCE_NAME, Constants.GROUPS_BYINCLUDE,
- createMock(AccountGroup.UUID.class))).isTrue();
+ mock(AccountGroup.UUID.class))).isTrue();
}
@Test
public void testEvictGroupsMembersOK() throws Exception {
- setupMocks(Constants.GROUPS_MEMBERS, EMPTY_JSON, true, false);
+ setupMocks(Constants.GROUPS_MEMBERS, EMPTY_JSON, OK_RESPONSE,
+ DO_NOT_THROW_EXCEPTION);
assertThat(restClient.evict(SOURCE_NAME, Constants.GROUPS_MEMBERS,
- createMock(AccountGroup.UUID.class))).isTrue();
+ mock(AccountGroup.UUID.class))).isTrue();
}
@Test
public void testEvictProjectListOK() throws Exception {
- setupMocks(Constants.PROJECT_LIST, EMPTY_JSON, true, false);
+ setupMocks(Constants.PROJECT_LIST, EMPTY_JSON, OK_RESPONSE,
+ DO_NOT_THROW_EXCEPTION);
assertThat(
restClient.evict(SOURCE_NAME, Constants.PROJECT_LIST, new Object()))
.isTrue();
@@ -83,14 +94,15 @@
@Test
public void testEvictCacheFailed() throws Exception {
- setupMocks(Constants.DEFAULT, EMPTY_JSON2, false, false);
+ setupMocks(Constants.DEFAULT, EMPTY_JSON2, FAIL_RESPONSE,
+ DO_NOT_THROW_EXCEPTION);
assertThat(restClient.evict(SOURCE_NAME, Constants.DEFAULT, EMPTY_JSON))
.isFalse();
}
@Test
public void testEvictCacheThrowsException() throws Exception {
- setupMocks(Constants.DEFAULT, EMPTY_JSON2, false, true);
+ setupMocks(Constants.DEFAULT, EMPTY_JSON2, FAIL_RESPONSE, THROW_EXCEPTION);
assertThat(restClient.evict(SOURCE_NAME, Constants.DEFAULT, EMPTY_JSON))
.isFalse();
}
@@ -99,14 +111,14 @@
boolean exception) throws IOException {
String request = Joiner.on("/").join("/plugins", PLUGIN_NAME, SOURCE_NAME,
EVICT, cacheName);
- HttpSession httpSession = createNiceMock(HttpSession.class);
+ HttpSession httpSession = mock(HttpSession.class);
if (exception) {
- expect(httpSession.post(request, json)).andThrow(new IOException());
+ doThrow(new IOException()).when(httpSession).post(request, json);
} else {
CacheResult result = new CacheResult(ok, "Error");
- expect(httpSession.post(request, json)).andReturn(result);
+ when(httpSession.post(request, json)).thenReturn(result);
}
- replayAll();
+
restClient = new RestSession(httpSession, PLUGIN_NAME);
}
}