Skip to content

Instantly share code, notes, and snippets.

@khatchad
Last active August 21, 2018 17:49
Show Gist options
  • Save khatchad/a0de2fb960def533c3854e0f49bfb917 to your computer and use it in GitHub Desktop.
Save khatchad/a0de2fb960def533c3854e0f49bfb917 to your computer and use it in GitHub Desktop.
Conversion of JUnit tests to JMH tests for java-design-patterns
diff --git a/abstract-document/src/test/java/com/iluwatar/abstractdocument/AbstractDocumentTest.java b/abstract-document/src/test/java/com/iluwatar/abstractdocument/AbstractDocumentTest.java
index b6467e232..aef824817 100644
--- a/abstract-document/src/test/java/com/iluwatar/abstractdocument/AbstractDocumentTest.java
+++ b/abstract-document/src/test/java/com/iluwatar/abstractdocument/AbstractDocumentTest.java
@@ -23,11 +23,18 @@
package com.iluwatar.abstractdocument;
import org.junit.Test;
+import org.openjdk.jmh.annotations.Benchmark;
+import org.openjdk.jmh.annotations.Level;
+import org.openjdk.jmh.annotations.Param;
+import org.openjdk.jmh.annotations.Scope;
+import org.openjdk.jmh.annotations.Setup;
+import org.openjdk.jmh.annotations.State;
-import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
import java.util.stream.Stream;
import static junit.framework.TestCase.assertEquals;
@@ -36,8 +43,12 @@ import static junit.framework.TestCase.assertNotNull;
/**
* AbstractDocument test class
*/
+@State(Scope.Benchmark)
public class AbstractDocumentTest {
+ @Param("1000000")
+ public int N;
+
private static final String KEY = "key";
private static final String VALUE = "value";
@@ -50,6 +61,13 @@ public class AbstractDocumentTest {
private DocumentImplementation document = new DocumentImplementation(new HashMap<>());
+ private List<Map<String, Object>> children;
+
+ @Setup(Level.Trial)
+ public void setUp() {
+ children = IntStream.range(0, N).mapToObj(i -> new HashMap<String, Object>()).collect(Collectors.toList());
+ }
+
@Test
public void shouldPutAndGetValue() {
document.put(KEY, VALUE);
@@ -57,16 +75,12 @@ public class AbstractDocumentTest {
}
@Test
+ @Benchmark
public void shouldRetrieveChildren() {
- Map<String, Object> child1 = new HashMap<>();
- Map<String, Object> child2 = new HashMap<>();
- List<Map<String, Object>> children = Arrays.asList(child1, child2);
-
document.put(KEY, children);
-
Stream<DocumentImplementation> childrenStream = document.children(KEY, DocumentImplementation::new);
assertNotNull(children);
- assertEquals(2, childrenStream.count());
+ assertEquals(N, childrenStream.count());
}
@Test
diff --git a/abstract-document/src/test/java/com/iluwatar/abstractdocument/DomainTest.java b/abstract-document/src/test/java/com/iluwatar/abstractdocument/DomainTest.java
index 437244a3d..1fd2e7a9f 100644
--- a/abstract-document/src/test/java/com/iluwatar/abstractdocument/DomainTest.java
+++ b/abstract-document/src/test/java/com/iluwatar/abstractdocument/DomainTest.java
@@ -29,9 +29,16 @@ import com.iluwatar.abstractdocument.domain.HasPrice;
import com.iluwatar.abstractdocument.domain.HasType;
import com.iluwatar.abstractdocument.domain.Part;
import org.junit.Test;
+import org.openjdk.jmh.annotations.Benchmark;
+import org.openjdk.jmh.annotations.Level;
+import org.openjdk.jmh.annotations.Param;
+import org.openjdk.jmh.annotations.Scope;
+import org.openjdk.jmh.annotations.Setup;
+import org.openjdk.jmh.annotations.State;
-import java.util.Arrays;
+import java.util.ArrayList;
import java.util.HashMap;
+import java.util.List;
import java.util.Map;
import static junit.framework.TestCase.assertEquals;
@@ -39,7 +46,11 @@ import static junit.framework.TestCase.assertEquals;
/**
* Test for Part and Car
*/
+@State(Scope.Benchmark)
public class DomainTest {
+
+ @Param("1000000")
+ public int N;
private static final String TEST_PART_TYPE = "test-part-type";
private static final String TEST_PART_MODEL = "test-part-model";
@@ -47,6 +58,7 @@ public class DomainTest {
private static final String TEST_CAR_MODEL = "test-car-model";
private static final long TEST_CAR_PRICE = 1L;
+ private Map<String, Object> carProperties;
@Test
public void shouldConstructPart() {
@@ -60,18 +72,30 @@ public class DomainTest {
assertEquals(TEST_PART_MODEL, part.getModel().get());
assertEquals(TEST_PART_PRICE, part.getPrice().get());
}
+
+ @Setup(Level.Trial)
+ public void setUp() {
+ carProperties = new HashMap<>();
+
+ carProperties.put(HasModel.PROPERTY, TEST_CAR_MODEL);
+ carProperties.put(HasPrice.PROPERTY, TEST_CAR_PRICE);
+
+ List<HashMap<Object, Object>> list = new ArrayList<>();
+
+ for (int i = 0; i < N; i++)
+ list.add(new HashMap<>());
+
+ carProperties.put(HasParts.PROPERTY, list);
+ }
@Test
+ @Benchmark
public void shouldConstructCar() {
- Map<String, Object> carProperties = new HashMap<>();
- carProperties.put(HasModel.PROPERTY, TEST_CAR_MODEL);
- carProperties.put(HasPrice.PROPERTY, TEST_CAR_PRICE);
- carProperties.put(HasParts.PROPERTY, Arrays.asList(new HashMap<>(), new HashMap<>()));
Car car = new Car(carProperties);
assertEquals(TEST_CAR_MODEL, car.getModel().get());
assertEquals(TEST_CAR_PRICE, car.getPrice().get());
- assertEquals(2, car.getParts().count());
+ assertEquals(N, car.getParts().count());
}
}
diff --git a/dao/src/main/java/com/iluwatar/dao/CustomerSchemaSql.java b/dao/src/main/java/com/iluwatar/dao/CustomerSchemaSql.java
index 860826abf..70baf7d8e 100644
--- a/dao/src/main/java/com/iluwatar/dao/CustomerSchemaSql.java
+++ b/dao/src/main/java/com/iluwatar/dao/CustomerSchemaSql.java
@@ -24,7 +24,7 @@ package com.iluwatar.dao;
public interface CustomerSchemaSql {
- String CREATE_SCHEMA_SQL = "CREATE TABLE CUSTOMERS (ID NUMBER, FNAME VARCHAR(100), "
+ String CREATE_SCHEMA_SQL = "DROP TABLE IF EXISTS CUSTOMERS;CREATE TABLE CUSTOMERS (ID NUMBER, FNAME VARCHAR(100), "
+ "LNAME VARCHAR(100))";
String DELETE_SCHEMA_SQL = "DROP TABLE CUSTOMERS";
diff --git a/dao/src/test/java/com/iluwatar/dao/ConnectionSuccess.java b/dao/src/test/java/com/iluwatar/dao/ConnectionSuccess.java
new file mode 100644
index 000000000..2121f8095
--- /dev/null
+++ b/dao/src/test/java/com/iluwatar/dao/ConnectionSuccess.java
@@ -0,0 +1,70 @@
+/**
+ * The MIT License
+ * Copyright (c) 2014 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+package com.iluwatar.dao;
+
+import static org.junit.Assert.assertTrue;
+
+import java.sql.SQLException;
+
+import org.h2.jdbcx.JdbcDataSource;
+import org.junit.After;
+import org.junit.Before;
+import org.openjdk.jmh.annotations.Level;
+import org.openjdk.jmh.annotations.Setup;
+import org.openjdk.jmh.annotations.TearDown;
+
+ /**
+ * Represents the scenario where DB connectivity is present.
+ */
+ public class ConnectionSuccess {
+
+ DbCustomerDaoTest dbCustomerDaoTest;
+ public int N;
+
+ /**
+ * Setup for connection success scenario.
+ * @throws Exception if any error occurs.
+ */
+ @Before
+ @Setup(Level.Invocation)
+ public void setUp() throws Exception {
+ dbCustomerDaoTest = new DbCustomerDaoTest();
+ dbCustomerDaoTest.createSchema();
+ dbCustomerDaoTest.N = N;
+ JdbcDataSource dataSource = new JdbcDataSource();
+ dataSource.setURL(DbCustomerDaoTest.DB_URL);
+ this.dbCustomerDaoTest.dao = new DbCustomerDao(dataSource);
+ boolean result = this.dbCustomerDaoTest.dao.add(DbCustomerDaoTest.EXISTING_CUSTOMER);
+ assertTrue(result);
+ for (int i = 0; i < this.dbCustomerDaoTest.N; i++) {
+ result = this.dbCustomerDaoTest.dao.add(new Customer(i + 1 + 1, "firstName", "lastName"));
+ assertTrue(result);
+ }
+ }
+
+ @After
+ @TearDown(Level.Invocation)
+ public void tearDown() throws SQLException {
+ this.dbCustomerDaoTest.deleteSchema();
+ }
+ }
diff --git a/dao/src/test/java/com/iluwatar/dao/DbCustomerDaoTest.java b/dao/src/test/java/com/iluwatar/dao/DbCustomerDaoTest.java
index ac69699df..147dab9b4 100644
--- a/dao/src/test/java/com/iluwatar/dao/DbCustomerDaoTest.java
+++ b/dao/src/test/java/com/iluwatar/dao/DbCustomerDaoTest.java
@@ -22,11 +22,8 @@
*/
package com.iluwatar.dao;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
-import static org.junit.Assume.assumeTrue;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
@@ -39,7 +36,6 @@ import java.util.stream.Stream;
import javax.sql.DataSource;
-import org.h2.jdbcx.JdbcDataSource;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
@@ -47,6 +43,12 @@ import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
+import org.openjdk.jmh.annotations.Level;
+import org.openjdk.jmh.annotations.Param;
+import org.openjdk.jmh.annotations.Scope;
+import org.openjdk.jmh.annotations.Setup;
+import org.openjdk.jmh.annotations.State;
+import org.openjdk.jmh.annotations.TearDown;
import de.bechte.junit.runners.context.HierarchicalContextRunner;
@@ -54,17 +56,20 @@ import de.bechte.junit.runners.context.HierarchicalContextRunner;
* Tests {@link DbCustomerDao}.
*/
@RunWith(HierarchicalContextRunner.class)
+@State(Scope.Benchmark)
public class DbCustomerDaoTest {
- private static final String DB_URL = "jdbc:h2:~/dao";
- private DbCustomerDao dao;
- private Customer existingCustomer = new Customer(1, "Freddy", "Krueger");
+ static final String DB_URL = "jdbc:h2:~/dao";
+ DbCustomerDao dao;
+ static final Customer EXISTING_CUSTOMER = new Customer(1, "Freddy", "Krueger");
+ public int N;
/**
* Creates customers schema.
* @throws SQLException if there is any error while creating schema.
*/
@Before
+ @Setup(Level.Invocation)
public void createSchema() throws SQLException {
try (Connection connection = DriverManager.getConnection(DB_URL);
Statement statement = connection.createStatement()) {
@@ -72,113 +77,6 @@ public class DbCustomerDaoTest {
}
}
- /**
- * Represents the scenario where DB connectivity is present.
- */
- public class ConnectionSuccess {
-
- /**
- * Setup for connection success scenario.
- * @throws Exception if any error occurs.
- */
- @Before
- public void setUp() throws Exception {
- JdbcDataSource dataSource = new JdbcDataSource();
- dataSource.setURL(DB_URL);
- dao = new DbCustomerDao(dataSource);
- boolean result = dao.add(existingCustomer);
- assertTrue(result);
- }
-
- /**
- * Represents the scenario when DAO operations are being performed on a non existing customer.
- */
- public class NonExistingCustomer {
-
- @Test
- public void addingShouldResultInSuccess() throws Exception {
- try (Stream<Customer> allCustomers = dao.getAll()) {
- assumeTrue(allCustomers.count() == 1);
- }
-
- final Customer nonExistingCustomer = new Customer(2, "Robert", "Englund");
- boolean result = dao.add(nonExistingCustomer);
- assertTrue(result);
-
- assertCustomerCountIs(2);
- assertEquals(nonExistingCustomer, dao.getById(nonExistingCustomer.getId()).get());
- }
-
- @Test
- public void deletionShouldBeFailureAndNotAffectExistingCustomers() throws Exception {
- final Customer nonExistingCustomer = new Customer(2, "Robert", "Englund");
- boolean result = dao.delete(nonExistingCustomer);
-
- assertFalse(result);
- assertCustomerCountIs(1);
- }
-
- @Test
- public void updationShouldBeFailureAndNotAffectExistingCustomers() throws Exception {
- final int nonExistingId = getNonExistingCustomerId();
- final String newFirstname = "Douglas";
- final String newLastname = "MacArthur";
- final Customer customer = new Customer(nonExistingId, newFirstname, newLastname);
- boolean result = dao.update(customer);
-
- assertFalse(result);
- assertFalse(dao.getById(nonExistingId).isPresent());
- }
-
- @Test
- public void retrieveShouldReturnNoCustomer() throws Exception {
- assertFalse(dao.getById(getNonExistingCustomerId()).isPresent());
- }
- }
-
- /**
- * Represents a scenario where DAO operations are being performed on an already existing
- * customer.
- *
- */
- public class ExistingCustomer {
-
- @Test
- public void addingShouldResultInFailureAndNotAffectExistingCustomers() throws Exception {
- Customer existingCustomer = new Customer(1, "Freddy", "Krueger");
-
- boolean result = dao.add(existingCustomer);
-
- assertFalse(result);
- assertCustomerCountIs(1);
- assertEquals(existingCustomer, dao.getById(existingCustomer.getId()).get());
- }
-
- @Test
- public void deletionShouldBeSuccessAndCustomerShouldBeNonAccessible() throws Exception {
- boolean result = dao.delete(existingCustomer);
-
- assertTrue(result);
- assertCustomerCountIs(0);
- assertFalse(dao.getById(existingCustomer.getId()).isPresent());
- }
-
- @Test
- public void updationShouldBeSuccessAndAccessingTheSameCustomerShouldReturnUpdatedInformation() throws Exception {
- final String newFirstname = "Bernard";
- final String newLastname = "Montgomery";
- final Customer customer = new Customer(existingCustomer.getId(), newFirstname, newLastname);
- boolean result = dao.update(customer);
-
- assertTrue(result);
-
- final Customer cust = dao.getById(existingCustomer.getId()).get();
- assertEquals(newFirstname, cust.getFirstName());
- assertEquals(newLastname, cust.getLastName());
- }
- }
- }
-
/**
* Represents a scenario where DB connectivity is not present due to network issue, or
* DB service unavailable.
@@ -216,7 +114,7 @@ public class DbCustomerDaoTest {
@Test
public void deletingACustomerFailsWithExceptionAsFeedbackToTheClient() throws Exception {
- dao.delete(existingCustomer);
+ dao.delete(EXISTING_CUSTOMER);
}
@Test
@@ -224,12 +122,12 @@ public class DbCustomerDaoTest {
final String newFirstname = "Bernard";
final String newLastname = "Montgomery";
- dao.update(new Customer(existingCustomer.getId(), newFirstname, newLastname));
+ dao.update(new Customer(EXISTING_CUSTOMER.getId(), newFirstname, newLastname));
}
@Test
public void retrievingACustomerByIdFailsWithExceptionAsFeedbackToClient() throws Exception {
- dao.getById(existingCustomer.getId());
+ dao.getById(EXISTING_CUSTOMER.getId());
}
@Test
@@ -244,6 +142,7 @@ public class DbCustomerDaoTest {
* @throws SQLException if any error occurs.
*/
@After
+ @TearDown(Level.Invocation)
public void deleteSchema() throws SQLException {
try (Connection connection = DriverManager.getConnection(DB_URL);
Statement statement = connection.createStatement()) {
@@ -251,7 +150,7 @@ public class DbCustomerDaoTest {
}
}
- private void assertCustomerCountIs(int count) throws Exception {
+ void assertCustomerCountIs(int count) throws Exception {
try (Stream<Customer> allCustomers = dao.getAll()) {
assertTrue(allCustomers.count() == count);
}
@@ -263,7 +162,7 @@ public class DbCustomerDaoTest {
*
* @return an int of a customer id which doesn't exist
*/
- private int getNonExistingCustomerId() {
- return 999;
+ int getNonExistingCustomerId() {
+ return N + 999;
}
}
diff --git a/dao/src/test/java/com/iluwatar/dao/ExistingCustomer.java b/dao/src/test/java/com/iluwatar/dao/ExistingCustomer.java
new file mode 100644
index 000000000..dde231c91
--- /dev/null
+++ b/dao/src/test/java/com/iluwatar/dao/ExistingCustomer.java
@@ -0,0 +1,106 @@
+/**
+ * The MIT License
+ * Copyright (c) 2014 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+package com.iluwatar.dao;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import java.util.Optional;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.openjdk.jmh.annotations.Benchmark;
+import org.openjdk.jmh.annotations.Level;
+import org.openjdk.jmh.annotations.Mode;
+import org.openjdk.jmh.annotations.Param;
+import org.openjdk.jmh.annotations.Scope;
+import org.openjdk.jmh.annotations.Setup;
+import org.openjdk.jmh.annotations.State;
+import org.openjdk.jmh.runner.Runner;
+import org.openjdk.jmh.runner.RunnerException;
+import org.openjdk.jmh.runner.options.Options;
+import org.openjdk.jmh.runner.options.OptionsBuilder;
+
+ /**
+ * Represents the scenario when the DAO operations are being performed on an already existing
+ * customer.
+ */
+ @State(Scope.Benchmark)
+ public class ExistingCustomer {
+
+ private InMemoryCustomerDaoTest inMemoryCustomerDaoTest;
+
+ @Param("1000000")
+ public int N;
+
+ @Setup(Level.Invocation)
+ @Before
+ public void setUp() {
+ this.inMemoryCustomerDaoTest = new InMemoryCustomerDaoTest();
+ this.inMemoryCustomerDaoTest.N = N;
+ this.inMemoryCustomerDaoTest.setUp();
+ }
+
+ @Test
+ @Benchmark
+ public void addingShouldResultInFailureAndNotAffectExistingCustomers() throws Exception {
+ boolean result = this.inMemoryCustomerDaoTest.dao.add(this.inMemoryCustomerDaoTest.CUSTOMER);
+
+ assertFalse(result);
+ this.inMemoryCustomerDaoTest.assertCustomerCountIs(this.inMemoryCustomerDaoTest.N + 1);
+ assertEquals(this.inMemoryCustomerDaoTest.CUSTOMER, this.inMemoryCustomerDaoTest.dao.getById(this.inMemoryCustomerDaoTest.CUSTOMER.getId()).get());
+ }
+
+ @Test
+ @Benchmark
+ public void deletionShouldBeSuccessAndCustomerShouldBeNonAccessible() throws Exception {
+ boolean result = this.inMemoryCustomerDaoTest.dao.delete(this.inMemoryCustomerDaoTest.CUSTOMER);
+
+ assertTrue(result);
+ this.inMemoryCustomerDaoTest.assertCustomerCountIs(this.inMemoryCustomerDaoTest.N);
+ assertFalse(this.inMemoryCustomerDaoTest.dao.getById(this.inMemoryCustomerDaoTest.CUSTOMER.getId()).isPresent());
+ }
+
+ @Test
+ public void updationShouldBeSuccessAndAccessingTheSameCustomerShouldReturnUpdatedInformation() throws Exception {
+ final String newFirstname = "Bernard";
+ final String newLastname = "Montgomery";
+ final Customer customer = new Customer(this.inMemoryCustomerDaoTest.CUSTOMER.getId(), newFirstname, newLastname);
+ boolean result = this.inMemoryCustomerDaoTest.dao.update(customer);
+
+ assertTrue(result);
+
+ final Customer cust = this.inMemoryCustomerDaoTest.dao.getById(this.inMemoryCustomerDaoTest.CUSTOMER.getId()).get();
+ assertEquals(newFirstname, cust.getFirstName());
+ assertEquals(newLastname, cust.getLastName());
+ }
+
+ @Test
+ public void retriveShouldReturnTheCustomer() {
+ Optional<Customer> optionalCustomer = this.inMemoryCustomerDaoTest.dao.getById(this.inMemoryCustomerDaoTest.CUSTOMER.getId());
+
+ assertTrue(optionalCustomer.isPresent());
+ assertEquals(this.inMemoryCustomerDaoTest.CUSTOMER, optionalCustomer.get());
+ }
+ }
diff --git a/dao/src/test/java/com/iluwatar/dao/ExistingCustomer2.java b/dao/src/test/java/com/iluwatar/dao/ExistingCustomer2.java
new file mode 100644
index 000000000..053efa19e
--- /dev/null
+++ b/dao/src/test/java/com/iluwatar/dao/ExistingCustomer2.java
@@ -0,0 +1,104 @@
+/**
+ * The MIT License
+ * Copyright (c) 2014 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+package com.iluwatar.dao;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import java.sql.SQLException;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.openjdk.jmh.annotations.Benchmark;
+import org.openjdk.jmh.annotations.Level;
+import org.openjdk.jmh.annotations.Param;
+import org.openjdk.jmh.annotations.Scope;
+import org.openjdk.jmh.annotations.Setup;
+import org.openjdk.jmh.annotations.State;
+import org.openjdk.jmh.annotations.TearDown;
+
+/**
+ * Represents a scenario where DAO operations are being performed on an already existing
+ * customer.
+ *
+ */
+@State(Scope.Benchmark)
+public class ExistingCustomer2 {
+
+ private ConnectionSuccess connectionSuccess;
+
+ @Param("1000")
+ public int N;
+
+ @Before
+ @Setup(Level.Invocation)
+ public void setUp() throws Exception {
+ this.connectionSuccess = new ConnectionSuccess();
+ this.connectionSuccess.N = N;
+ this.connectionSuccess.setUp();
+ }
+
+ @After
+ @TearDown(Level.Invocation)
+ public void tearDown() throws SQLException {
+ this.connectionSuccess.tearDown();
+ }
+
+ @Test
+ @Benchmark
+ public void addingShouldResultInFailureAndNotAffectExistingCustomers() throws Exception {
+ Customer existingCustomer = new Customer(1, "Freddy", "Krueger");
+
+ boolean result = this.connectionSuccess.dbCustomerDaoTest.dao.add(existingCustomer);
+
+ assertFalse(result);
+ this.connectionSuccess.dbCustomerDaoTest.assertCustomerCountIs(this.connectionSuccess.dbCustomerDaoTest.N + 1);
+ assertEquals(existingCustomer, this.connectionSuccess.dbCustomerDaoTest.dao.getById(existingCustomer.getId()).get());
+ }
+
+ @Test
+ @Benchmark
+ public void deletionShouldBeSuccessAndCustomerShouldBeNonAccessible() throws Exception {
+ boolean result = this.connectionSuccess.dbCustomerDaoTest.dao.delete(DbCustomerDaoTest.EXISTING_CUSTOMER);
+
+ assertTrue(result);
+ this.connectionSuccess.dbCustomerDaoTest.assertCustomerCountIs(this.connectionSuccess.dbCustomerDaoTest.N);
+ assertFalse(this.connectionSuccess.dbCustomerDaoTest.dao.getById(DbCustomerDaoTest.EXISTING_CUSTOMER.getId()).isPresent());
+ }
+
+ @Test
+ public void updationShouldBeSuccessAndAccessingTheSameCustomerShouldReturnUpdatedInformation() throws Exception {
+ final String newFirstname = "Bernard";
+ final String newLastname = "Montgomery";
+ final Customer customer = new Customer(DbCustomerDaoTest.EXISTING_CUSTOMER.getId(), newFirstname, newLastname);
+ boolean result = this.connectionSuccess.dbCustomerDaoTest.dao.update(customer);
+
+ assertTrue(result);
+
+ final Customer cust = this.connectionSuccess.dbCustomerDaoTest.dao.getById(DbCustomerDaoTest.EXISTING_CUSTOMER.getId()).get();
+ assertEquals(newFirstname, cust.getFirstName());
+ assertEquals(newLastname, cust.getLastName());
+ }
+}
diff --git a/dao/src/test/java/com/iluwatar/dao/InMemoryCustomerDaoTest.java b/dao/src/test/java/com/iluwatar/dao/InMemoryCustomerDaoTest.java
index 65a087b9b..2ea81af85 100644
--- a/dao/src/test/java/com/iluwatar/dao/InMemoryCustomerDaoTest.java
+++ b/dao/src/test/java/com/iluwatar/dao/InMemoryCustomerDaoTest.java
@@ -23,18 +23,19 @@
package com.iluwatar.dao;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
-import static org.junit.Assume.assumeTrue;
-import java.util.Optional;
+import java.util.stream.IntStream;
import java.util.stream.Stream;
import org.junit.Before;
-import org.junit.Test;
import org.junit.runner.RunWith;
+import org.openjdk.jmh.annotations.Level;
+import org.openjdk.jmh.annotations.Param;
+import org.openjdk.jmh.annotations.Scope;
+import org.openjdk.jmh.annotations.Setup;
+import org.openjdk.jmh.annotations.State;
import de.bechte.junit.runners.context.HierarchicalContextRunner;
@@ -42,109 +43,19 @@ import de.bechte.junit.runners.context.HierarchicalContextRunner;
* Tests {@link InMemoryCustomerDao}.
*/
@RunWith(HierarchicalContextRunner.class)
+@State(Scope.Benchmark)
public class InMemoryCustomerDaoTest {
- private InMemoryCustomerDao dao;
- private static final Customer CUSTOMER = new Customer(1, "Freddy", "Krueger");
+ InMemoryCustomerDao dao;
+ static final Customer CUSTOMER = new Customer(1, "Freddy", "Krueger");
+ public int N;
@Before
+ @Setup(Level.Invocation)
public void setUp() {
dao = new InMemoryCustomerDao();
assertTrue(dao.add(CUSTOMER));
- }
-
- /**
- * Represents the scenario when the DAO operations are being performed on a non existent
- * customer.
- */
- public class NonExistingCustomer {
-
- @Test
- public void addingShouldResultInSuccess() throws Exception {
- try (Stream<Customer> allCustomers = dao.getAll()) {
- assumeTrue(allCustomers.count() == 1);
- }
-
- final Customer nonExistingCustomer = new Customer(2, "Robert", "Englund");
- boolean result = dao.add(nonExistingCustomer);
- assertTrue(result);
-
- assertCustomerCountIs(2);
- assertEquals(nonExistingCustomer, dao.getById(nonExistingCustomer.getId()).get());
- }
-
- @Test
- public void deletionShouldBeFailureAndNotAffectExistingCustomers() throws Exception {
- final Customer nonExistingCustomer = new Customer(2, "Robert", "Englund");
- boolean result = dao.delete(nonExistingCustomer);
-
- assertFalse(result);
- assertCustomerCountIs(1);
- }
-
- @Test
- public void updationShouldBeFailureAndNotAffectExistingCustomers() throws Exception {
- final int nonExistingId = getNonExistingCustomerId();
- final String newFirstname = "Douglas";
- final String newLastname = "MacArthur";
- final Customer customer = new Customer(nonExistingId, newFirstname, newLastname);
- boolean result = dao.update(customer);
-
- assertFalse(result);
- assertFalse(dao.getById(nonExistingId).isPresent());
- }
-
- @Test
- public void retrieveShouldReturnNoCustomer() throws Exception {
- assertFalse(dao.getById(getNonExistingCustomerId()).isPresent());
- }
- }
-
- /**
- * Represents the scenario when the DAO operations are being performed on an already existing
- * customer.
- */
- public class ExistingCustomer {
-
- @Test
- public void addingShouldResultInFailureAndNotAffectExistingCustomers() throws Exception {
- boolean result = dao.add(CUSTOMER);
-
- assertFalse(result);
- assertCustomerCountIs(1);
- assertEquals(CUSTOMER, dao.getById(CUSTOMER.getId()).get());
- }
-
- @Test
- public void deletionShouldBeSuccessAndCustomerShouldBeNonAccessible() throws Exception {
- boolean result = dao.delete(CUSTOMER);
-
- assertTrue(result);
- assertCustomerCountIs(0);
- assertFalse(dao.getById(CUSTOMER.getId()).isPresent());
- }
-
- @Test
- public void updationShouldBeSuccessAndAccessingTheSameCustomerShouldReturnUpdatedInformation() throws Exception {
- final String newFirstname = "Bernard";
- final String newLastname = "Montgomery";
- final Customer customer = new Customer(CUSTOMER.getId(), newFirstname, newLastname);
- boolean result = dao.update(customer);
-
- assertTrue(result);
-
- final Customer cust = dao.getById(CUSTOMER.getId()).get();
- assertEquals(newFirstname, cust.getFirstName());
- assertEquals(newLastname, cust.getLastName());
- }
-
- @Test
- public void retriveShouldReturnTheCustomer() {
- Optional<Customer> optionalCustomer = dao.getById(CUSTOMER.getId());
-
- assertTrue(optionalCustomer.isPresent());
- assertEquals(CUSTOMER, optionalCustomer.get());
- }
+ IntStream.range(0, N).forEach(n -> assertTrue(dao.add(new Customer(n + 1 + 1, "firstName", "lastName"))));
}
/**
@@ -152,11 +63,11 @@ public class InMemoryCustomerDaoTest {
*
* @return an int of a customer id which doesn't exist
*/
- private int getNonExistingCustomerId() {
- return 999;
+ int getNonExistingCustomerId() {
+ return N + 999;
}
- private void assertCustomerCountIs(int count) throws Exception {
+ void assertCustomerCountIs(int count) throws Exception {
try (Stream<Customer> allCustomers = dao.getAll()) {
assertTrue(allCustomers.count() == count);
}
diff --git a/dao/src/test/java/com/iluwatar/dao/NonExistingCustomer.java b/dao/src/test/java/com/iluwatar/dao/NonExistingCustomer.java
new file mode 100644
index 000000000..69ca6972a
--- /dev/null
+++ b/dao/src/test/java/com/iluwatar/dao/NonExistingCustomer.java
@@ -0,0 +1,103 @@
+/**
+ * The MIT License
+ * Copyright (c) 2014 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+package com.iluwatar.dao;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assume.assumeTrue;
+
+import java.util.stream.Stream;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.openjdk.jmh.annotations.Benchmark;
+import org.openjdk.jmh.annotations.Level;
+import org.openjdk.jmh.annotations.Param;
+import org.openjdk.jmh.annotations.Scope;
+import org.openjdk.jmh.annotations.Setup;
+import org.openjdk.jmh.annotations.State;
+
+ /**
+ * Represents the scenario when the DAO operations are being performed on a non existent
+ * customer.
+ */
+ @State(Scope.Benchmark)
+ public class NonExistingCustomer {
+
+ private InMemoryCustomerDaoTest inMemoryCustomerDaoTest;
+
+ @Param("1000000")
+ public int N;
+
+ @Setup(Level.Invocation)
+ @Before
+ public void setUp() {
+ this.inMemoryCustomerDaoTest = new InMemoryCustomerDaoTest();
+ this.inMemoryCustomerDaoTest.N = N;
+ this.inMemoryCustomerDaoTest.setUp();
+ }
+
+ @Test
+ @Benchmark
+ public void addingShouldResultInSuccess() throws Exception {
+ try (Stream<Customer> allCustomers = this.inMemoryCustomerDaoTest.dao.getAll()) {
+ boolean test = allCustomers.count() == this.inMemoryCustomerDaoTest.N + 1;
+ assumeTrue(test);
+ }
+
+ final Customer nonExistingCustomer = new Customer(this.inMemoryCustomerDaoTest.N + 2, "Robert", "Englund");
+ boolean result = this.inMemoryCustomerDaoTest.dao.add(nonExistingCustomer);
+ assertTrue(result);
+
+ this.inMemoryCustomerDaoTest.assertCustomerCountIs(this.inMemoryCustomerDaoTest.N + 2);
+ assertEquals(nonExistingCustomer, this.inMemoryCustomerDaoTest.dao.getById(nonExistingCustomer.getId()).get());
+ }
+
+ @Test
+ @Benchmark
+ public void deletionShouldBeFailureAndNotAffectExistingCustomers() throws Exception {
+ final Customer nonExistingCustomer = new Customer(this.inMemoryCustomerDaoTest.N + 2, "Robert", "Englund");
+ boolean result = this.inMemoryCustomerDaoTest.dao.delete(nonExistingCustomer);
+
+ assertFalse(result);
+ this.inMemoryCustomerDaoTest.assertCustomerCountIs(this.inMemoryCustomerDaoTest.N + 1);
+ }
+
+ @Test
+ public void updationShouldBeFailureAndNotAffectExistingCustomers() throws Exception {
+ final int nonExistingId = this.inMemoryCustomerDaoTest.getNonExistingCustomerId();
+ final String newFirstname = "Douglas";
+ final String newLastname = "MacArthur";
+ final Customer customer = new Customer(nonExistingId, newFirstname, newLastname);
+ boolean result = this.inMemoryCustomerDaoTest.dao.update(customer);
+
+ assertFalse(result);
+ assertFalse(this.inMemoryCustomerDaoTest.dao.getById(nonExistingId).isPresent());
+ }
+
+ @Test
+ public void retrieveShouldReturnNoCustomer() throws Exception {
+ assertFalse(this.inMemoryCustomerDaoTest.dao.getById(this.inMemoryCustomerDaoTest.getNonExistingCustomerId()).isPresent());
+ }
+ }
diff --git a/dao/src/test/java/com/iluwatar/dao/NonExistingCustomer2.java b/dao/src/test/java/com/iluwatar/dao/NonExistingCustomer2.java
new file mode 100644
index 000000000..505427269
--- /dev/null
+++ b/dao/src/test/java/com/iluwatar/dao/NonExistingCustomer2.java
@@ -0,0 +1,110 @@
+/**
+ * The MIT License
+ * Copyright (c) 2014 Ilkka Seppälä
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+package com.iluwatar.dao;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assume.assumeTrue;
+
+import java.sql.SQLException;
+import java.util.stream.Stream;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.openjdk.jmh.annotations.Benchmark;
+import org.openjdk.jmh.annotations.Level;
+import org.openjdk.jmh.annotations.Param;
+import org.openjdk.jmh.annotations.Scope;
+import org.openjdk.jmh.annotations.Setup;
+import org.openjdk.jmh.annotations.State;
+import org.openjdk.jmh.annotations.TearDown;
+
+/**
+ * Represents the scenario when DAO operations are being performed on a non existing customer.
+ */
+@State(Scope.Benchmark)
+public class NonExistingCustomer2 {
+
+ private ConnectionSuccess connectionSuccess;
+
+ @Param("1000")
+ public int N;
+
+ @Before
+ @Setup(Level.Invocation)
+ public void setUp() throws Exception {
+ this.connectionSuccess = new ConnectionSuccess();
+ this.connectionSuccess.N = N;
+ this.connectionSuccess.setUp();
+ }
+
+ @After
+ @TearDown(Level.Invocation)
+ public void tearDown() throws SQLException {
+ this.connectionSuccess.tearDown();
+ }
+
+ @Test
+ @Benchmark
+ public void addingShouldResultInSuccess() throws Exception {
+ try (Stream<Customer> allCustomers = this.connectionSuccess.dbCustomerDaoTest.dao.getAll()) {
+ assumeTrue(allCustomers.count() == this.connectionSuccess.dbCustomerDaoTest.N + 1);
+ }
+
+ final Customer nonExistingCustomer = new Customer(this.connectionSuccess.dbCustomerDaoTest.N + 2, "Robert", "Englund");
+ boolean result = this.connectionSuccess.dbCustomerDaoTest.dao.add(nonExistingCustomer);
+ assertTrue(result);
+
+ this.connectionSuccess.dbCustomerDaoTest.assertCustomerCountIs(this.connectionSuccess.dbCustomerDaoTest.N + 2);
+ assertEquals(nonExistingCustomer, this.connectionSuccess.dbCustomerDaoTest.dao.getById(nonExistingCustomer.getId()).get());
+ }
+
+ @Test
+ @Benchmark
+ public void deletionShouldBeFailureAndNotAffectExistingCustomers() throws Exception {
+ final Customer nonExistingCustomer = new Customer(this.connectionSuccess.dbCustomerDaoTest.N + 2, "Robert", "Englund");
+ boolean result = this.connectionSuccess.dbCustomerDaoTest.dao.delete(nonExistingCustomer);
+
+ assertFalse(result);
+ this.connectionSuccess.dbCustomerDaoTest.assertCustomerCountIs(this.connectionSuccess.dbCustomerDaoTest.N + 1);
+ }
+
+ @Test
+ public void updationShouldBeFailureAndNotAffectExistingCustomers() throws Exception {
+ final int nonExistingId = this.connectionSuccess.dbCustomerDaoTest.getNonExistingCustomerId();
+ final String newFirstname = "Douglas";
+ final String newLastname = "MacArthur";
+ final Customer customer = new Customer(nonExistingId, newFirstname, newLastname);
+ boolean result = this.connectionSuccess.dbCustomerDaoTest.dao.update(customer);
+
+ assertFalse(result);
+ assertFalse(this.connectionSuccess.dbCustomerDaoTest.dao.getById(nonExistingId).isPresent());
+ }
+
+ @Test
+ public void retrieveShouldReturnNoCustomer() throws Exception {
+ assertFalse(this.connectionSuccess.dbCustomerDaoTest.dao.getById(this.connectionSuccess.dbCustomerDaoTest.getNonExistingCustomerId()).isPresent());
+ }
+}
diff --git a/double-dispatch/src/main/java/com/iluwatar/doubledispatch/App.java b/double-dispatch/src/main/java/com/iluwatar/doubledispatch/App.java
index 3a4a26b99..4e075af52 100644
--- a/double-dispatch/src/main/java/com/iluwatar/doubledispatch/App.java
+++ b/double-dispatch/src/main/java/com/iluwatar/doubledispatch/App.java
@@ -51,13 +51,7 @@ public class App {
* @param args
* command line args
*/
- @edu.cuny.hunter.streamrefactoring.annotations.EntryPoint public static void main(String[] args) {
- // initialize game objects and print their status
- List<GameObject> objects = new ArrayList<>();
- objects.add(new FlamingAsteroid(0, 0, 5, 5));
- objects.add(new SpaceStationMir(1, 1, 2, 2));
- objects.add(new Meteoroid(10, 10, 15, 15));
- objects.add(new SpaceStationIss(12, 12, 14, 14));
+ @edu.cuny.hunter.streamrefactoring.annotations.EntryPoint public static void main(String[] args, List<GameObject> objects) {
objects.stream().forEach(o -> System.out.println(o));
System.out.println("");
diff --git a/double-dispatch/src/test/java/com/iluwatar/doubledispatch/AppTest.java b/double-dispatch/src/test/java/com/iluwatar/doubledispatch/AppTest.java
index c1a6aa690..2def4916c 100644
--- a/double-dispatch/src/test/java/com/iluwatar/doubledispatch/AppTest.java
+++ b/double-dispatch/src/test/java/com/iluwatar/doubledispatch/AppTest.java
@@ -22,18 +22,47 @@
*/
package com.iluwatar.doubledispatch;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.stream.IntStream;
+
+import org.junit.Before;
import org.junit.Test;
+import org.openjdk.jmh.annotations.Benchmark;
+import org.openjdk.jmh.annotations.Level;
+import org.openjdk.jmh.annotations.Param;
+import org.openjdk.jmh.annotations.Scope;
+import org.openjdk.jmh.annotations.Setup;
+import org.openjdk.jmh.annotations.State;
/**
*
* Application test
*
*/
+@State(Scope.Benchmark)
public class AppTest {
+ @Param("1000")
+ public int N;
+ private List<GameObject> objects;
+
+ @Before
+ @Setup(Level.Invocation)
+ public void setUp() {
+ objects = new ArrayList<>();
+ IntStream.range(0, N).forEachOrdered(i -> {
+ objects.add(new FlamingAsteroid(0, 0, 5, 5));
+ objects.add(new SpaceStationMir(1, 1, 2, 2));
+ objects.add(new Meteoroid(10, 10, 15, 15));
+ objects.add(new SpaceStationIss(12, 12, 14, 14));
+ });
+ }
+
@Test
+ @Benchmark
public void test() {
String[] args = {};
- App.main(args);
+ App.main(args, objects);
}
}
diff --git a/pom.xml b/pom.xml
index 13020543b..f661446f7 100644
--- a/pom.xml
+++ b/pom.xml
@@ -47,6 +47,8 @@
<hierarchical-junit-runner-version>4.12.1</hierarchical-junit-runner-version>
<apache-httpcomponents.version>4.5.2</apache-httpcomponents.version>
<htmlunit.version>2.22</htmlunit.version>
+ <jmh.version>1.21</jmh.version>
+ <uberjar.name>benchmarks</uberjar.name>
</properties>
<modules>
<module>abstract-factory</module>
@@ -251,6 +253,17 @@
<artifactId>edu.cuny.hunter.streamrefactoring.annotations</artifactId>
<version>1.0.0</version>
</dependency>
+ <dependency>
+ <groupId>org.openjdk.jmh</groupId>
+ <artifactId>jmh-core</artifactId>
+ <version>${jmh.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>org.openjdk.jmh</groupId>
+ <artifactId>jmh-generator-annprocess</artifactId>
+ <version>${jmh.version}</version>
+ <scope>provided</scope>
+ </dependency>
</dependencies>
<build>
@@ -301,6 +314,41 @@
<target>1.8</target>
</configuration>
</plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-shade-plugin</artifactId>
+ <version>2.2</version>
+ <executions>
+ <execution>
+ <phase>package</phase>
+ <goals>
+ <goal>shade</goal>
+ </goals>
+ <configuration>
+ <finalName>${uberjar.name}</finalName>
+ <transformers>
+ <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
+ <mainClass>org.openjdk.jmh.Main</mainClass>
+ </transformer>
+ </transformers>
+ <filters>
+ <filter>
+ <!--
+ Shading signed JARs will fail without this.
+ http://stackoverflow.com/questions/999489/invalid-signature-file-when-attempting-to-run-a-jar
+ -->
+ <artifact>*:*</artifact>
+ <excludes>
+ <exclude>META-INF/*.SF</exclude>
+ <exclude>META-INF/*.DSA</exclude>
+ <exclude>META-INF/*.RSA</exclude>
+ </excludes>
+ </filter>
+ </filters>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
<plugin>
<groupId>org.eluder.coveralls</groupId>
<artifactId>coveralls-maven-plugin</artifactId>
@@ -436,6 +484,57 @@
</execution>
</executions>
</plugin>
+ <plugin>
+ <groupId>org.codehaus.mojo</groupId>
+ <artifactId>exec-maven-plugin</artifactId>
+ <executions>
+ <execution>
+ <id>run-benchmarks</id>
+ <phase>integration-test</phase>
+ <goals>
+ <goal>exec</goal>
+ </goals>
+ <configuration>
+ <classpathScope>test</classpathScope>
+ <executable>java</executable>
+ <arguments>
+ <argument>-classpath</argument>
+ <classpath />
+ <argument>org.openjdk.jmh.Main</argument>
+ <argument>.*</argument>
+ <argument>-bm</argument>
+ <argument>avgt</argument>
+ <argument>-f</argument>
+ <argument>1</argument>
+ <argument>-tu</argument>
+ <argument>ms</argument>
+ <argument>-rff</argument>
+ <argument>jmh-results.csv</argument>
+ <argument>-o</argument>
+ <argument>jmh-results.txt</argument>
+ </arguments>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
</plugins>
</build>
diff --git a/specification/src/main/java/com/iluwatar/specification/app/App.java b/specification/src/main/java/com/iluwatar/specification/app/App.java
index a8188831d..83a2c77a3 100644
--- a/specification/src/main/java/com/iluwatar/specification/app/App.java
+++ b/specification/src/main/java/com/iluwatar/specification/app/App.java
@@ -22,9 +22,11 @@
*/
package com.iluwatar.specification.app;
+import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
+import java.util.stream.IntStream;
import com.iluwatar.specification.creature.Creature;
import com.iluwatar.specification.creature.Dragon;
@@ -53,31 +55,37 @@ import com.iluwatar.specification.selector.MovementSelector;
*/
public class App {
+ private static List<Creature> creatures = new ArrayList<>();
+
/**
* Program entry point
*/
@edu.cuny.hunter.streamrefactoring.annotations.EntryPoint public static void main(String[] args) {
- // initialize creatures list
- List<Creature> creatures =
- Arrays.asList(new Goblin(), new Octopus(), new Dragon(), new Shark(), new Troll(),
- new KillerBee());
// find all walking creatures
- System.out.println("Find all walking creatures");
+// System.out.println("Find all walking creatures");
List<Creature> walkingCreatures =
creatures.stream().filter(new MovementSelector(Movement.WALKING))
.collect(Collectors.toList());
- walkingCreatures.stream().forEach(System.out::println);
+// walkingCreatures.stream().forEach(System.out::println);
// find all dark creatures
- System.out.println("Find all dark creatures");
+// System.out.println("Find all dark creatures");
List<Creature> darkCreatures =
creatures.stream().filter(new ColorSelector(Color.DARK)).collect(Collectors.toList());
- darkCreatures.stream().forEach(System.out::println);
+// darkCreatures.stream().forEach(System.out::println);
// find all red and flying creatures
- System.out.println("Find all red and flying creatures");
+// System.out.println("Find all red and flying creatures");
List<Creature> redAndFlyingCreatures =
creatures.stream()
.filter(new ColorSelector(Color.RED).and(new MovementSelector(Movement.FLYING)))
.collect(Collectors.toList());
- redAndFlyingCreatures.stream().forEach(System.out::println);
+// redAndFlyingCreatures.stream().forEach(System.out::println);
+ }
+
+ public static void initialize(int N) {
+ IntStream.range(0, N).forEach(i -> {
+ List<Creature> list = Arrays.asList(new Goblin(), new Octopus(), new Dragon(), new Shark(), new Troll(),
+ new KillerBee());
+ creatures.addAll(list);
+ });
}
}
diff --git a/specification/src/test/java/com/iluwatar/specification/app/AppTest.java b/specification/src/test/java/com/iluwatar/specification/app/AppTest.java
index 13e6c9b5d..35d8ebe04 100644
--- a/specification/src/test/java/com/iluwatar/specification/app/AppTest.java
+++ b/specification/src/test/java/com/iluwatar/specification/app/AppTest.java
@@ -22,16 +22,34 @@
*/
package com.iluwatar.specification.app;
+import org.junit.Before;
import org.junit.Test;
+import org.openjdk.jmh.annotations.Benchmark;
+import org.openjdk.jmh.annotations.Level;
+import org.openjdk.jmh.annotations.Param;
+import org.openjdk.jmh.annotations.Scope;
+import org.openjdk.jmh.annotations.Setup;
+import org.openjdk.jmh.annotations.State;
/**
*
* Application test
*
*/
+@State(Scope.Benchmark)
public class AppTest {
+ @Param("1000000")
+ public int N;
+
+ @Before
+ @Setup(Level.Invocation)
+ public void setUp() {
+ App.initialize(N);
+ }
+
@Test
+ @Benchmark
public void test() {
String[] args = {};
App.main(args);
diff --git a/thread-pool/src/test/java/com/iluwatar/threadpool/CoffeeMakingTaskTest.java b/thread-pool/src/test/java/com/iluwatar/threadpool/CoffeeMakingTaskTest.java
index 281ef16ad..7ade8a70c 100644
--- a/thread-pool/src/test/java/com/iluwatar/threadpool/CoffeeMakingTaskTest.java
+++ b/thread-pool/src/test/java/com/iluwatar/threadpool/CoffeeMakingTaskTest.java
@@ -22,18 +22,41 @@
*/
package com.iluwatar.threadpool;
+import org.openjdk.jmh.annotations.State;
+import org.openjdk.jmh.annotations.Benchmark;
+import org.openjdk.jmh.annotations.Level;
+import org.openjdk.jmh.annotations.Param;
+import org.openjdk.jmh.annotations.Scope;
+import org.openjdk.jmh.annotations.Setup;
+
/**
* Date: 12/30/15 - 18:23 PM
*
* @author Jeroen Meulemeester
*/
+@State(Scope.Benchmark)
public class CoffeeMakingTaskTest extends TaskTest<CoffeeMakingTask> {
+ @Param("1000000")
+ public int N;
+
/**
* Create a new test instance
*/
public CoffeeMakingTaskTest() {
super(CoffeeMakingTask::new, 100);
}
+
+ @Setup(Level.Invocation)
+ public void setUp() {
+ this.taskCount = N;
+ super.setUp();
+ }
+
+ @Override
+ @Benchmark
+ public void testIdGeneration() throws Exception {
+ super.testIdGeneration();
+ }
}
diff --git a/thread-pool/src/test/java/com/iluwatar/threadpool/PotatoPeelingTaskTest.java b/thread-pool/src/test/java/com/iluwatar/threadpool/PotatoPeelingTaskTest.java
index d27e6ba5d..d30256491 100644
--- a/thread-pool/src/test/java/com/iluwatar/threadpool/PotatoPeelingTaskTest.java
+++ b/thread-pool/src/test/java/com/iluwatar/threadpool/PotatoPeelingTaskTest.java
@@ -22,18 +22,40 @@
*/
package com.iluwatar.threadpool;
+import org.openjdk.jmh.annotations.Benchmark;
+import org.openjdk.jmh.annotations.Level;
+import org.openjdk.jmh.annotations.Param;
+import org.openjdk.jmh.annotations.Scope;
+import org.openjdk.jmh.annotations.Setup;
+import org.openjdk.jmh.annotations.State;
+
/**
* Date: 12/30/15 - 18:23 PM
*
* @author Jeroen Meulemeester
*/
+@State(Scope.Benchmark)
public class PotatoPeelingTaskTest extends TaskTest<PotatoPeelingTask> {
+ @Param("1000000")
+ public int N;
+
/**
* Create a new test instance
*/
public PotatoPeelingTaskTest() {
super(PotatoPeelingTask::new, 200);
}
-
+
+ @Setup(Level.Invocation)
+ public void setUp() {
+ this.taskCount = N;
+ super.setUp();
+ }
+
+ @Override
+ @Benchmark
+ public void testIdGeneration() throws Exception {
+ super.testIdGeneration();
+ }
}
diff --git a/thread-pool/src/test/java/com/iluwatar/threadpool/TaskTest.java b/thread-pool/src/test/java/com/iluwatar/threadpool/TaskTest.java
index 9f2ff5721..b301015f9 100644
--- a/thread-pool/src/test/java/com/iluwatar/threadpool/TaskTest.java
+++ b/thread-pool/src/test/java/com/iluwatar/threadpool/TaskTest.java
@@ -22,6 +22,7 @@
*/
package com.iluwatar.threadpool;
+import org.junit.BeforeClass;
import org.junit.Test;
import edu.cuny.hunter.streamrefactoring.annotations.EntryPoint;
@@ -50,12 +51,12 @@ public class TaskTest<T extends Task> {
/**
* The number of tasks used during the concurrency test
*/
- private static final int TASK_COUNT = 128 * 1024;
+ protected int taskCount;
/**
* The number of threads used during the concurrency test
*/
- private static final int THREAD_COUNT = 8;
+ private static final int THREAD_COUNT = 1;
/**
* The task factory, used to create new test items
@@ -67,6 +68,10 @@ public class TaskTest<T extends Task> {
*/
private final int expectedExecutionTime;
+ private ExecutorService service;
+
+ private List<Callable<Integer>> tasks;
+
/**
* Create a new test instance
*
@@ -84,13 +89,6 @@ public class TaskTest<T extends Task> {
*/
@Test(timeout = 10000) @EntryPoint
public void testIdGeneration() throws Exception {
- final ExecutorService service = Executors.newFixedThreadPool(THREAD_COUNT);
-
- final List<Callable<Integer>> tasks = new ArrayList<>();
- for (int i = 0; i < TASK_COUNT; i++) {
- tasks.add(() -> factory.apply(1).getId());
- }
-
final List<Integer> ids = service.invokeAll(tasks)
.stream()
.map(TaskTest::get)
@@ -103,11 +101,21 @@ public class TaskTest<T extends Task> {
.distinct()
.count();
- assertEquals(TASK_COUNT, ids.size());
- assertEquals(TASK_COUNT, uniqueIdCount);
+ assertEquals(taskCount, ids.size());
+ assertEquals(taskCount, uniqueIdCount);
}
+ @BeforeClass
+ public void setUp() {
+ service = Executors.newFixedThreadPool(THREAD_COUNT);
+
+ tasks = new ArrayList<>();
+ for (int i = 0; i < taskCount; i++) {
+ tasks.add(() -> factory.apply(1).getId());
+ }
+ }
+
/**
* Verify if the time per execution of a task matches the actual time required to execute the task
* a given number of times
@@ -142,4 +150,4 @@ public class TaskTest<T extends Task> {
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment