From abaa0ef7cfb5faad2518f9f3e3ce8e35f18aef6f Mon Sep 17 00:00:00 2001 From: Alex Golub Date: Sat, 14 Jan 2023 18:08:53 +0200 Subject: [PATCH 01/16] Bump to Groovy `3.0.8` --- core-groovy-modules/core-groovy-2/pom.xml | 7 ++++--- core-groovy-modules/core-groovy-collections/pom.xml | 8 +++++--- core-groovy-modules/core-groovy-strings/pom.xml | 7 ++++--- core-groovy-modules/core-groovy/pom.xml | 8 +++++--- core-groovy-modules/pom.xml | 10 +++++----- 5 files changed, 23 insertions(+), 17 deletions(-) diff --git a/core-groovy-modules/core-groovy-2/pom.xml b/core-groovy-modules/core-groovy-2/pom.xml index a177844a15..2b864ec7a1 100644 --- a/core-groovy-modules/core-groovy-2/pom.xml +++ b/core-groovy-modules/core-groovy-2/pom.xml @@ -155,8 +155,9 @@ - central - https://jcenter.bintray.com + maven_central + Maven Central + https://repo.maven.apache.org/maven2/ @@ -167,4 +168,4 @@ 3.3.0-01 - \ No newline at end of file + diff --git a/core-groovy-modules/core-groovy-collections/pom.xml b/core-groovy-modules/core-groovy-collections/pom.xml index 5269121140..6d43ce7d18 100644 --- a/core-groovy-modules/core-groovy-collections/pom.xml +++ b/core-groovy-modules/core-groovy-collections/pom.xml @@ -113,9 +113,11 @@ - central - http://jcenter.bintray.com + maven_central + Maven Central + https://repo.maven.apache.org/maven2/ - \ No newline at end of file + + diff --git a/core-groovy-modules/core-groovy-strings/pom.xml b/core-groovy-modules/core-groovy-strings/pom.xml index e51ebfbd4b..fac0f25219 100644 --- a/core-groovy-modules/core-groovy-strings/pom.xml +++ b/core-groovy-modules/core-groovy-strings/pom.xml @@ -103,9 +103,10 @@ - central - https://jcenter.bintray.com + maven_central + Maven Central + https://repo.maven.apache.org/maven2/ - \ No newline at end of file + diff --git a/core-groovy-modules/core-groovy/pom.xml b/core-groovy-modules/core-groovy/pom.xml index 413fbde106..cf6cca9e18 100644 --- a/core-groovy-modules/core-groovy/pom.xml +++ b/core-groovy-modules/core-groovy/pom.xml @@ -3,6 +3,7 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 + core-groovy 1.0-SNAPSHOT core-groovy @@ -103,9 +104,10 @@ - central - https://jcenter.bintray.com + maven_central + Maven Central + https://repo.maven.apache.org/maven2/ - \ No newline at end of file + diff --git a/core-groovy-modules/pom.xml b/core-groovy-modules/pom.xml index e1ff538942..2d1120e435 100644 --- a/core-groovy-modules/pom.xml +++ b/core-groovy-modules/pom.xml @@ -21,12 +21,12 @@ - 2.5.7 - 2.5.6 - 2.5.6 + 3.0.8 + 3.0.8 + 3.0.8 2.4.0 - 1.1-groovy-2.4 + 2.3-groovy-3.0 1.6 - \ No newline at end of file + From 85775f930a01ea452ba39381b07773d854604e16 Mon Sep 17 00:00:00 2001 From: Alex Golub Date: Sat, 14 Jan 2023 18:09:17 +0200 Subject: [PATCH 02/16] SQL queries conventions --- .../com/baeldung/groovy/sql/SqlTest.groovy | 52 +++++++++++-------- 1 file changed, 29 insertions(+), 23 deletions(-) diff --git a/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/groovy/sql/SqlTest.groovy b/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/groovy/sql/SqlTest.groovy index ac96a55773..da982744e9 100644 --- a/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/groovy/sql/SqlTest.groovy +++ b/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/groovy/sql/SqlTest.groovy @@ -1,28 +1,29 @@ package com.baeldung.groovy.sql import groovy.sql.GroovyResultSet -import groovy.sql.GroovyRowResult import groovy.sql.Sql -import groovy.transform.CompileStatic -import static org.junit.Assert.* import org.junit.Test +import static org.junit.Assert.* + class SqlTest { - final Map dbConnParams = [url: 'jdbc:hsqldb:mem:testDB', user: 'sa', password: '', driver: 'org.hsqldb.jdbc.JDBCDriver'] + final Map dbConnParams = [url: 'jdbc:hsqldb:mem:testDB', + user: 'sa', + password: '', + driver: 'org.hsqldb.jdbc.JDBCDriver'] @Test void whenNewSqlInstance_thenDbIsAccessed() { def sql = Sql.newInstance(dbConnParams) sql.close() - sql.close() } @Test void whenTableDoesNotExist_thenSelectFails() { try { Sql.withInstance(dbConnParams) { Sql sql -> - sql.eachRow('select * from PROJECT') {} + sql.eachRow('SELECT * FROM PROJECT') {} } fail("An exception should have been thrown") @@ -34,12 +35,12 @@ class SqlTest { @Test void whenTableCreated_thenSelectIsPossible() { Sql.withInstance(dbConnParams) { Sql sql -> - def result = sql.execute 'create table PROJECT_1 (id integer not null, name varchar(50), url varchar(100))' + def result = sql.execute 'CREATE TABLE PROJECT_1 (ID INTEGER NOT NULL, NAME VARCHAR(50), URL VARCHAR(100))' assertEquals(0, sql.updateCount) assertFalse(result) - result = sql.execute('select * from PROJECT_1') + result = sql.execute('SELECT * FROM PROJECT_1') assertTrue(result) } @@ -48,7 +49,7 @@ class SqlTest { @Test void whenIdentityColumn_thenInsertReturnsNewId() { Sql.withInstance(dbConnParams) { Sql sql -> - sql.execute 'create table PROJECT_2 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))' + sql.execute 'CREATE TABLE PROJECT_2 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))' def ids = sql.executeInsert("INSERT INTO PROJECT_2 (NAME, URL) VALUES ('tutorials', 'github.com/eugenp/tutorials')") assertEquals(0, ids[0][0]) @@ -62,9 +63,10 @@ class SqlTest { @Test void whenUpdate_thenNumberOfAffectedRows() { Sql.withInstance(dbConnParams) { Sql sql -> - sql.execute 'create table PROJECT_3 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))' + sql.execute 'CREATE TABLE PROJECT_3 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))' sql.executeInsert("INSERT INTO PROJECT_3 (NAME, URL) VALUES ('tutorials', 'github.com/eugenp/tutorials')") sql.executeInsert("INSERT INTO PROJECT_3 (NAME, URL) VALUES ('REST with Spring', 'github.com/eugenp/REST-With-Spring')") + def count = sql.executeUpdate("UPDATE PROJECT_3 SET URL = 'https://' + URL") assertEquals(2, count) @@ -74,7 +76,7 @@ class SqlTest { @Test void whenEachRow_thenResultSetHasProperties() { Sql.withInstance(dbConnParams) { Sql sql -> - sql.execute 'create table PROJECT_4 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))' + sql.execute 'CREATE TABLE PROJECT_4 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))' sql.executeInsert("INSERT INTO PROJECT_4 (NAME, URL) VALUES ('tutorials', 'https://github.com/eugenp/tutorials')") sql.executeInsert("INSERT INTO PROJECT_4 (NAME, URL) VALUES ('REST with Spring', 'https://github.com/eugenp/REST-With-Spring')") @@ -93,7 +95,7 @@ class SqlTest { @Test void whenPagination_thenSubsetIsReturned() { Sql.withInstance(dbConnParams) { Sql sql -> - sql.execute 'create table PROJECT_5 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))' + sql.execute 'CREATE TABLE PROJECT_5 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))' sql.executeInsert("INSERT INTO PROJECT_5 (NAME, URL) VALUES ('tutorials', 'github.com/eugenp/tutorials')") sql.executeInsert("INSERT INTO PROJECT_5 (NAME, URL) VALUES ('REST with Spring', 'github.com/eugenp/REST-With-Spring')") def rows = sql.rows('SELECT * FROM PROJECT_5 ORDER BY NAME', 1, 1) @@ -106,9 +108,11 @@ class SqlTest { @Test void whenParameters_thenReplacement() { Sql.withInstance(dbConnParams) { Sql sql -> - sql.execute 'create table PROJECT_6 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))' - sql.execute('INSERT INTO PROJECT_6 (NAME, URL) VALUES (?, ?)', 'tutorials', 'github.com/eugenp/tutorials') - sql.execute("INSERT INTO PROJECT_6 (NAME, URL) VALUES (:name, :url)", [name: 'REST with Spring', url: 'github.com/eugenp/REST-With-Spring']) + sql.execute 'CREATE TABLE PROJECT_6 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))' + sql.execute('INSERT INTO PROJECT_6 (NAME, URL) VALUES (?, ?)', + 'tutorials', 'github.com/eugenp/tutorials') + sql.execute("INSERT INTO PROJECT_6 (NAME, URL) VALUES (:name, :url)", + [name: 'REST with Spring', url: 'github.com/eugenp/REST-With-Spring']) def rows = sql.rows("SELECT * FROM PROJECT_6 WHERE NAME = 'tutorials'") @@ -123,7 +127,7 @@ class SqlTest { @Test void whenParametersInGString_thenReplacement() { Sql.withInstance(dbConnParams) { Sql sql -> - sql.execute 'create table PROJECT_7 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))' + sql.execute 'CREATE TABLE PROJECT_7 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))' sql.execute "INSERT INTO PROJECT_7 (NAME, URL) VALUES (${'tutorials'}, ${'github.com/eugenp/tutorials'})" def name = 'REST with Spring' def url = 'github.com/eugenp/REST-With-Spring' @@ -143,7 +147,7 @@ class SqlTest { void whenTransactionRollback_thenNoDataInserted() { Sql.withInstance(dbConnParams) { Sql sql -> sql.withTransaction { - sql.execute 'create table PROJECT_8 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))' + sql.execute 'CREATE TABLE PROJECT_8 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))' sql.executeInsert("INSERT INTO PROJECT_8 (NAME, URL) VALUES ('tutorials', 'https://github.com/eugenp/tutorials')") sql.executeInsert("INSERT INTO PROJECT_8 (NAME, URL) VALUES ('REST with Spring', 'https://github.com/eugenp/REST-With-Spring')") sql.rollback() @@ -159,7 +163,7 @@ class SqlTest { void whenTransactionRollbackThenCommit_thenOnlyLastInserted() { Sql.withInstance(dbConnParams) { Sql sql -> sql.withTransaction { - sql.execute 'create table PROJECT_9 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))' + sql.execute 'CREATE TABLE PROJECT_9 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))' sql.executeInsert("INSERT INTO PROJECT_9 (NAME, URL) VALUES ('tutorials', 'https://github.com/eugenp/tutorials')") sql.rollback() sql.executeInsert("INSERT INTO PROJECT_9 (NAME, URL) VALUES ('REST with Spring', 'https://github.com/eugenp/REST-With-Spring')") @@ -179,11 +183,12 @@ class SqlTest { Sql.withInstance(dbConnParams) { Sql sql -> try { sql.withTransaction { - sql.execute 'create table PROJECT_10 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))' + sql.execute 'CREATE TABLE PROJECT_10 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))' sql.executeInsert("INSERT INTO PROJECT_10 (NAME, URL) VALUES ('tutorials', 'https://github.com/eugenp/tutorials')") throw new Exception('rollback') } - } catch (ignored) {} + } catch (ignored) { + } def rows = sql.rows("SELECT * FROM PROJECT_10") @@ -196,11 +201,12 @@ class SqlTest { Sql.withInstance(dbConnParams) { Sql sql -> try { sql.cacheConnection { - sql.execute 'create table PROJECT_11 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))' + sql.execute 'CREATE TABLE PROJECT_11 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))' sql.executeInsert("INSERT INTO PROJECT_11 (NAME, URL) VALUES ('tutorials', 'https://github.com/eugenp/tutorials')") throw new Exception('This does not rollback') } - } catch (ignored) {} + } catch (ignored) { + } def rows = sql.rows("SELECT * FROM PROJECT_11") @@ -211,7 +217,7 @@ class SqlTest { /*@Test void whenModifyResultSet_thenDataIsChanged() { Sql.withInstance(dbConnParams) { Sql sql -> - sql.execute 'create table PROJECT_5 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))' + sql.execute 'CREATE TABLE PROJECT_5 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))' sql.executeInsert("INSERT INTO PROJECT_5 (NAME, URL) VALUES ('tutorials', 'github.com/eugenp/tutorials')") sql.executeInsert("INSERT INTO PROJECT_5 (NAME, URL) VALUES ('REST with Spring', 'github.com/eugenp/REST-With-Spring')") From ab5c09a958eb9174556f8be8cb8152580e649dac Mon Sep 17 00:00:00 2001 From: Alex Golub Date: Sat, 14 Jan 2023 18:11:19 +0200 Subject: [PATCH 03/16] Test `JsonGenerator` --- .../com/baeldung/json/JsonParserTest.groovy | 58 ++++++++++++++----- 1 file changed, 43 insertions(+), 15 deletions(-) diff --git a/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/json/JsonParserTest.groovy b/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/json/JsonParserTest.groovy index e65550a3be..fa7b2fd3c8 100644 --- a/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/json/JsonParserTest.groovy +++ b/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/json/JsonParserTest.groovy @@ -1,5 +1,6 @@ package com.baeldung.json +import groovy.json.JsonGenerator import spock.lang.Specification import java.text.SimpleDateFormat @@ -8,20 +9,42 @@ class JsonParserTest extends Specification { JsonParser jsonParser - void setup () { + void setup() { jsonParser = new JsonParser() } - def 'Should parse to Account given Json String' () { + def 'Should parse to Account given Json String'() { given: - def json = '{"id":"1234","value":15.6}' + def json = '{"id":"1234","value":15.6}' + when: - def account = jsonParser.toObject(json) + def account = jsonParser.toObject(json) + then: - account - account instanceof Account - account.id == '1234' - account.value == 15.6 + account + account instanceof Account + account.id == '1234' + account.value == 15.6 + } + + def 'Should format date and exclude value field'() { + given: + def account = new Account( + id: '123', + value: 15.6, + createdAt: new SimpleDateFormat('MM/dd/yyyy').parse('14/01/2023') + ) + + def jsonGenerator = new JsonGenerator.Options() + .dateFormat('MM/dd/yyyy') + .excludeFieldsByName('value') + .build() + + when: + def accountToJson = jsonGenerator.toJson(account) + + then: + accountToJson == '{"createdAt":"01/31/2024","id":"123"}' } /*def 'Should parse to Account given Json String with date property' () { @@ -52,15 +75,20 @@ class JsonParserTest extends Specification { json == '{"value":15.6,"createdAt":"2018-01-01T00:00:00+0000","id":"123"}' }*/ - def 'Should prettify given a json string' () { + def 'Should prettify given a json string'() { given: - String json = '{"value":15.6,"createdAt":"01/01/2018","id":"123456"}' + String json = '{"value":15.6,"createdAt":"01/01/2018","id":"123456"}' + when: - def jsonPretty = jsonParser.prettyfy(json) + def jsonPretty = jsonParser.prettyfy(json) + then: - jsonPretty - jsonPretty == '{\n "value": 15.6,\n "createdAt": "01/01/2018",\n "id": "123456"\n}' + jsonPretty + jsonPretty == '''\ +{ + "value": 15.6, + "createdAt": "01/01/2018", + "id": "123456" +}''' } - - } From f3a20f71294591544a1283b3da66e67cade6e482 Mon Sep 17 00:00:00 2001 From: Alex Golub Date: Sat, 14 Jan 2023 21:31:29 +0200 Subject: [PATCH 04/16] Align tests with `Spock` testing framework --- .../com/baeldung/strings/Concatenate.groovy | 24 ++- .../baeldung/strings/ConcatenateTest.groovy | 149 ++++++++---------- .../strings/StringMatchingSpec.groovy | 2 +- .../stringtoint/ConvertStringToInt.groovy | 131 ++++++++------- .../stringtypes/CharacterInGroovy.groovy | 17 +- .../stringtypes/DoubleQuotedString.groovy | 63 ++++---- .../stringtypes/SingleQuotedString.groovy | 15 +- .../com/baeldung/stringtypes/Strings.groovy | 21 +-- 8 files changed, 218 insertions(+), 204 deletions(-) diff --git a/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/strings/Concatenate.groovy b/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/strings/Concatenate.groovy index b3a0852a0b..4a7c3f8529 100644 --- a/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/strings/Concatenate.groovy +++ b/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/strings/Concatenate.groovy @@ -1,9 +1,10 @@ package com.baeldung.strings; class Concatenate { + String first = 'Hello' String last = 'Groovy' - + String doSimpleConcat() { return 'My name is ' + first + ' ' + last } @@ -23,21 +24,28 @@ class Concatenate { String doConcatUsingLeftShiftOperator() { return 'My name is ' << first << ' ' << last } - + String doConcatUsingArrayJoinMethod() { return ['My name is', first, last].join(' ') } String doConcatUsingArrayInjectMethod() { - return [first,' ', last] - .inject(new StringBuffer('My name is '), { initial, name -> initial.append(name); return initial }).toString() + return [first, ' ', last] + .inject(new StringBuffer('My name is '), { initial, name -> initial.append(name) }) + .toString() } - + String doConcatUsingStringBuilder() { - return new StringBuilder().append('My name is ').append(first).append(' ').append(last) + return new StringBuilder().append('My name is ') + .append(first) + .append(' ') + .append(last) } String doConcatUsingStringBuffer() { - return new StringBuffer().append('My name is ').append(first).append(' ').append(last) + return new StringBuffer().append('My name is ') + .append(first) + .append(' ') + .append(last) } -} \ No newline at end of file +} diff --git a/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/strings/ConcatenateTest.groovy b/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/strings/ConcatenateTest.groovy index 3ef4a5d460..e4a178a14b 100644 --- a/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/strings/ConcatenateTest.groovy +++ b/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/strings/ConcatenateTest.groovy @@ -1,101 +1,88 @@ -import com.baeldung.strings.Concatenate; +import com.baeldung.strings.Concatenate +import spock.lang.Specification -class ConcatenateTest extends GroovyTestCase { - - void testSimpleConcat() { - def name = new Concatenate() - name.first = 'Joe'; - name.last = 'Smith'; - def expected = 'My name is Joe Smith' - assertToString(name.doSimpleConcat(), expected) - } - - void testConcatUsingGString() { - def name = new Concatenate() - name.first = "Joe"; - name.last = "Smith"; - def expected = "My name is Joe Smith" - assertToString(name.doConcatUsingGString(), expected) - } - - void testConcatUsingGStringClosures() { - def name = new Concatenate() - name.first = "Joe"; - name.last = "Smith"; - def expected = "My name is Joe Smith" - assertToString(name.doConcatUsingGStringClosures(), expected) - } - - void testConcatUsingStringConcatMethod() { - def name = new Concatenate() - name.first = "Joe"; - name.last = "Smith"; - def expected = "My name is Joe Smith" - assertToString(name.doConcatUsingStringConcatMethod(), expected) +class ConcatenateTest extends Specification { + + final Concatenate NAME = new Concatenate(first: 'Joe', last: 'Smith') + final String EXPECTED = "My name is Joe Smith"; + + def "SimpleConcat"() { + expect: + NAME.doSimpleConcat() == EXPECTED } - void testConcatUsingLeftShiftOperator() { - def name = new Concatenate() - name.first = "Joe"; - name.last = "Smith"; - def expected = "My name is Joe Smith" - assertToString(name.doConcatUsingLeftShiftOperator(), expected) + def "ConcatUsingGString"() { + expect: + NAME.doConcatUsingGString() == EXPECTED } - void testConcatUsingArrayJoinMethod() { - def name = new Concatenate() - name.first = "Joe"; - name.last = "Smith"; - def expected = "My name is Joe Smith" - assertToString(name.doConcatUsingArrayJoinMethod(), expected) + def "ConcatUsingGStringClosures"() { + expect: + NAME.doConcatUsingGStringClosures() == EXPECTED } - void testConcatUsingArrayInjectMethod() { - def name = new Concatenate() - name.first = "Joe"; - name.last = "Smith"; - def expected = "My name is Joe Smith" - assertToString(name.doConcatUsingArrayInjectMethod(), expected) + def "ConcatUsingStringConcatMethod"() { + expect: + NAME.doConcatUsingStringConcatMethod() == EXPECTED } - void testConcatUsingStringBuilder() { - def name = new Concatenate() - name.first = "Joe"; - name.last = "Smith"; - def expected = "My name is Joe Smith" - assertToString(name.doConcatUsingStringBuilder(), expected) + def "ConcatUsingLeftShiftOperator"() { + expect: + NAME.doConcatUsingLeftShiftOperator() == EXPECTED } - void testConcatUsingStringBuffer() { - def name = new Concatenate() - name.first = "Joe"; - name.last = "Smith"; - def expected = "My name is Joe Smith" - assertToString(name.doConcatUsingStringBuffer(), expected) + def "ConcatUsingArrayJoinMethod"() { + expect: + NAME.doConcatUsingArrayJoinMethod() == EXPECTED } - void testConcatMultilineUsingStringConcatMethod() { - def name = new Concatenate() - name.first = '''Joe + def "ConcatUsingArrayInjectMethod"() { + expect: + NAME.doConcatUsingArrayInjectMethod() == EXPECTED + } + + def "ConcatUsingStringBuilder"() { + expect: + NAME.doConcatUsingStringBuilder() == EXPECTED + } + + def "ConcatUsingStringBuffer"() { + expect: + NAME.doConcatUsingStringBuffer() == EXPECTED + } + + def "ConcatMultilineUsingStringConcatMethod"() { + when: + NAME.first = '''Joe Smith - '''; - name.last = 'Junior'; + ''' + NAME.last = 'Junior' + + then: def expected = '''My name is Joe Smith - Junior'''; - assertToString(name.doConcatUsingStringConcatMethod(), expected) + Junior''' + NAME.doConcatUsingStringConcatMethod() == expected } - void testGStringvsClosure(){ - def first = "Joe"; - def last = "Smith"; - def eagerGString = "My name is $first $last" - def lazyGString = "My name is ${-> first} ${-> last}" + def "GStringvsClosure"() { + given: + def eagerGString = "My name is $NAME.first $NAME.last" + def lazyGString = "My name is ${-> NAME.first} ${-> NAME.last}" - assert eagerGString == "My name is Joe Smith" - assert lazyGString == "My name is Joe Smith" - first = "David"; - assert eagerGString == "My name is Joe Smith" - assert lazyGString == "My name is David Smith" - } + expect: + eagerGString == "My name is Joe Smith" + lazyGString == "My name is Joe Smith" + } + + def "LazyVsEager"() { + given: + def eagerGString = "My name is $NAME.first $NAME.last" + def lazyGString = "My name is ${-> NAME.first} ${-> NAME.last}" + NAME.first = "David" + + expect: + eagerGString == "My name is Joe Smith" + lazyGString == "My name is David Smith" + } } diff --git a/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/strings/StringMatchingSpec.groovy b/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/strings/StringMatchingSpec.groovy index 3865bc73fa..89202d9500 100644 --- a/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/strings/StringMatchingSpec.groovy +++ b/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/strings/StringMatchingSpec.groovy @@ -13,7 +13,7 @@ class StringMatchingSpec extends Specification { expect: p instanceof Pattern - and: "you can use slash strings to avoid escaping of blackslash" + and: "you can use slash strings to avoid escaping of backslash" def digitPattern = ~/\d*/ digitPattern.matcher('4711').matches() } diff --git a/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/stringtoint/ConvertStringToInt.groovy b/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/stringtoint/ConvertStringToInt.groovy index 48cf48fa8a..cce6ede989 100644 --- a/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/stringtoint/ConvertStringToInt.groovy +++ b/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/stringtoint/ConvertStringToInt.groovy @@ -1,110 +1,119 @@ package com.baeldung.stringtoint -import org.junit.Test +import spock.lang.Specification import java.text.DecimalFormat -import static org.junit.Assert.assertEquals -import static org.junit.Assert.assertNull +class ConvertStringToInt extends Specification { -class ConvertStringToInt { + final String STRING_NUM = "123" + final int EXPECTED_INT = 123 - @Test - void givenString_whenUsingAsInteger_thenConvertToInteger() { - def stringNum = "123" + def "givenString_whenUsingAsInteger_thenConvertToInteger"() { + given: def invalidString = "123a" - Integer expectedInteger = 123 - Integer integerNum = stringNum as Integer + Integer integerNum = STRING_NUM as Integer + + when: def intNum = invalidString?.isInteger() ? invalidString as Integer : null - assertNull(null, intNum) - assertEquals(integerNum, expectedInteger) + then: + intNum == null + integerNum == EXPECTED_INT } - @Test - void givenString_whenUsingAsInt_thenConvertToInt() { - def stringNum = "123" - int expectedInt = 123 - int intNum = stringNum as int + def "givenString_whenUsingAsInt_thenConvertToInt"() { + given: + int intNum = STRING_NUM as int - assertEquals(intNum, expectedInt) + expect: + intNum == EXPECTED_INT } - @Test - void givenString_whenUsingToInteger_thenConvertToInteger() { - def stringNum = "123" - int expectedInt = 123 - int intNum = stringNum.toInteger() + def "givenString_whenUsingToInteger_thenConvertToInteger"() { + given: + int intNum = STRING_NUM.toInteger() - assertEquals(intNum, expectedInt) + expect: + intNum == EXPECTED_INT } - @Test - void givenString_whenUsingParseInt_thenConvertToInteger() { - def stringNum = "123" - int expectedInt = 123 - int intNum = Integer.parseInt(stringNum) + def "givenString_whenUsingParseInt_thenConvertToInteger"() { + given: + int intNum = Integer.parseInt(STRING_NUM) - assertEquals(intNum, expectedInt) + expect: + intNum == EXPECTED_INT } - @Test - void givenString_whenUsingValueOf_thenConvertToInteger() { - def stringNum = "123" - int expectedInt = 123 - int intNum = Integer.valueOf(stringNum) + def "givenString_whenUsingValueOf_thenConvertToInteger"() { + given: + int intNum = Integer.valueOf(STRING_NUM) - assertEquals(intNum, expectedInt) + expect: + intNum == EXPECTED_INT } - @Test - void givenString_whenUsingIntValue_thenConvertToInteger() { - def stringNum = "123" - int expectedInt = 123 - int intNum = new Integer(stringNum).intValue() + def "givenString_whenUsingIntValue_thenConvertToInteger"() { + given: + int intNum = Integer.valueOf(STRING_NUM).intValue() - assertEquals(intNum, expectedInt) + expect: + intNum == EXPECTED_INT } - @Test - void givenString_whenUsingNewInteger_thenConvertToInteger() { - def stringNum = "123" - int expectedInt = 123 - int intNum = new Integer(stringNum) + def "givenString_whenUsingNewInteger_thenConvertToInteger"() { + given: + Integer intNum = Integer.valueOf(STRING_NUM) - assertEquals(intNum, expectedInt) + expect: + intNum == EXPECTED_INT } - @Test - void givenString_whenUsingDecimalFormat_thenConvertToInteger() { - def stringNum = "123" - int expectedInt = 123 + def "givenString_whenUsingDecimalFormat_thenConvertToInteger"() { + given: DecimalFormat decimalFormat = new DecimalFormat("#") - int intNum = decimalFormat.parse(stringNum).intValue() - assertEquals(intNum, expectedInt) + when: + int intNum = decimalFormat.parse(STRING_NUM).intValue() + + then: + intNum == EXPECTED_INT } - @Test(expected = NumberFormatException.class) - void givenInvalidString_whenUsingAs_thenThrowNumberFormatException() { + def "givenInvalidString_whenUsingAs_thenThrowNumberFormatException"() { + given: def invalidString = "123a" + + when: invalidString as Integer + + then: + thrown(NumberFormatException) } - @Test(expected = NullPointerException.class) - void givenNullString_whenUsingToInteger_thenThrowNullPointerException() { + def "givenNullString_whenUsingToInteger_thenThrowNullPointerException"() { + given: def invalidString = null + + when: invalidString.toInteger() + + then: + thrown(NullPointerException) } - @Test - void givenString_whenUsingIsInteger_thenCheckIfCorrectValue() { + def "givenString_whenUsingIsInteger_thenCheckIfCorrectValue"() { + given: def invalidString = "123a" def validString = "123" + + when: def invalidNum = invalidString?.isInteger() ? invalidString as Integer : false def correctNum = validString?.isInteger() ? validString as Integer : false - assertEquals(false, invalidNum) - assertEquals(123, correctNum) + then: + !invalidNum + correctNum == 123 } } diff --git a/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/stringtypes/CharacterInGroovy.groovy b/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/stringtypes/CharacterInGroovy.groovy index c043723d95..30365ec9d7 100644 --- a/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/stringtypes/CharacterInGroovy.groovy +++ b/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/stringtypes/CharacterInGroovy.groovy @@ -1,19 +1,18 @@ package groovy.com.baeldung.stringtypes -import org.junit.Assert -import org.junit.Test +import spock.lang.Specification -class CharacterInGroovy { +class CharacterInGroovy extends Specification { - @Test - void 'character'() { + def 'character'() { + given: char a = 'A' as char char b = 'B' as char char c = (char) 'C' - Assert.assertTrue(a instanceof Character) - Assert.assertTrue(b instanceof Character) - Assert.assertTrue(c instanceof Character) + expect: + a instanceof Character + b instanceof Character + c instanceof Character } - } diff --git a/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/stringtypes/DoubleQuotedString.groovy b/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/stringtypes/DoubleQuotedString.groovy index a730244d0a..e1074145f4 100644 --- a/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/stringtypes/DoubleQuotedString.groovy +++ b/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/stringtypes/DoubleQuotedString.groovy @@ -1,67 +1,76 @@ package groovy.com.baeldung.stringtypes -import org.junit.Assert -import org.junit.Test +import spock.lang.Specification -class DoubleQuotedString { +class DoubleQuotedString extends Specification { - @Test - void 'escape double quoted string'() { + def 'escape double quoted string'() { + given: def example = "Hello \"world\"!" - println(example) + expect: + example == 'Hello "world"!' } - @Test - void 'String ang GString'() { + def 'String ang GString'() { + given: def string = "example" def stringWithExpression = "example${2}" - Assert.assertTrue(string instanceof String) - Assert.assertTrue(stringWithExpression instanceof GString) - Assert.assertTrue(stringWithExpression.toString() instanceof String) + expect: + string instanceof String + stringWithExpression instanceof GString + stringWithExpression.toString() instanceof String } - @Test - void 'placeholder with variable'() { + def 'placeholder with variable'() { + given: def name = "John" + + when: def helloName = "Hello $name!".toString() - Assert.assertEquals("Hello John!", helloName) + then: + helloName == "Hello John!" } - @Test - void 'placeholder with expression'() { + def 'placeholder with expression'() { + given: def result = "result is ${2 * 2}".toString() - Assert.assertEquals("result is 4", result) + expect: + result == "result is 4" } - @Test - void 'placeholder with dotted access'() { + def 'placeholder with dotted access'() { + given: def person = [name: 'John'] + when: def myNameIs = "I'm $person.name, and you?".toString() - Assert.assertEquals("I'm John, and you?", myNameIs) + then: + myNameIs == "I'm John, and you?" } - @Test - void 'placeholder with method call'() { + def 'placeholder with method call'() { + given: def name = 'John' + when: def result = "Uppercase name: ${name.toUpperCase()}".toString() - Assert.assertEquals("Uppercase name: JOHN", result) + then: + result == "Uppercase name: JOHN" } - @Test - void 'GString and String hashcode'() { + def 'GString and String hashcode'() { + given: def string = "2+2 is 4" def gstring = "2+2 is ${4}" - Assert.assertTrue(string.hashCode() != gstring.hashCode()) + expect: + string.hashCode() != gstring.hashCode() } - } diff --git a/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/stringtypes/SingleQuotedString.groovy b/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/stringtypes/SingleQuotedString.groovy index 569991b788..924515570c 100644 --- a/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/stringtypes/SingleQuotedString.groovy +++ b/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/stringtypes/SingleQuotedString.groovy @@ -1,15 +1,14 @@ package groovy.com.baeldung.stringtypes -import org.junit.Assert -import org.junit.Test +import spock.lang.Specification -class SingleQuotedString { +class SingleQuotedString extends Specification { - @Test - void 'single quoted string'() { - def example = 'Hello world' + def 'single quoted string'() { + given: + def example = 'Hello world!' - Assert.assertEquals('Hello world!', 'Hello' + ' world!') + expect: + example == 'Hello' + ' world!' } - } diff --git a/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/stringtypes/Strings.groovy b/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/stringtypes/Strings.groovy index e45f352285..9d29210d81 100644 --- a/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/stringtypes/Strings.groovy +++ b/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/stringtypes/Strings.groovy @@ -1,26 +1,29 @@ package groovy.com.baeldung.stringtypes -import org.junit.Assert -import org.junit.Test +import spock.lang.Specification -class Strings { +class Strings extends Specification { - @Test - void 'string interpolation '() { + def 'string interpolation '() { + given: def name = "Kacper" + when: def result = "Hello ${name}!" - Assert.assertEquals("Hello Kacper!", result.toString()) + then: + result.toString() == "Hello Kacper!" } - @Test - void 'string concatenation'() { + def 'string concatenation'() { + given: def first = "first" def second = "second" + when: def concatenation = first + second - Assert.assertEquals("firstsecond", concatenation) + then: + concatenation == "firstsecond" } } From c34a4ac328d606f223b590f838ed77ad4b81cd70 Mon Sep 17 00:00:00 2001 From: Alex Golub Date: Sat, 14 Jan 2023 19:50:22 +0200 Subject: [PATCH 05/16] Reformat and single liner `read*` methods --- .../groovy/com/baeldung/file/ReadFile.groovy | 62 +++++------- .../com/baeldung/file/ReadFileUnitTest.groovy | 99 ++++++++++--------- 2 files changed, 78 insertions(+), 83 deletions(-) diff --git a/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/file/ReadFile.groovy b/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/file/ReadFile.groovy index 4239fa534c..1418947cc7 100644 --- a/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/file/ReadFile.groovy +++ b/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/file/ReadFile.groovy @@ -10,13 +10,14 @@ class ReadFile { int readFileLineByLine(String filePath) { File file = new File(filePath) def line, noOfLines = 0; + file.withReader { reader -> - while ((line = reader.readLine())!=null) - { + while ((line = reader.readLine()) != null) { println "${line}" noOfLines++ } } + return noOfLines } @@ -26,9 +27,7 @@ class ReadFile { * @return */ List readFileInList(String filePath) { - File file = new File(filePath) - def lines = file.readLines() - return lines + return new File(filePath).readLines() } /** @@ -37,9 +36,7 @@ class ReadFile { * @return */ String readFileString(String filePath) { - File file = new File(filePath) - String fileContent = file.text - return fileContent + return new File(filePath).text } /** @@ -48,9 +45,7 @@ class ReadFile { * @return */ String readFileStringWithCharset(String filePath) { - File file = new File(filePath) - String utf8Content = file.getText("UTF-8") - return utf8Content + return new File(filePath).getText("UTF-8") } /** @@ -59,49 +54,44 @@ class ReadFile { * @return */ byte[] readBinaryFile(String filePath) { - File file = new File(filePath) - byte[] binaryContent = file.bytes - return binaryContent + return new File(filePath).bytes } - + /** * More Examples of reading a file * @return */ def moreExamples() { - + //with reader with utf-8 new File("src/main/resources/utf8Content.html").withReader('UTF-8') { reader -> def line - while ((line = reader.readLine())!=null) { + while ((line = reader.readLine()) != null) { println "${line}" } } - - //collect api - def list = new File("src/main/resources/fileContent.txt").collect {it} - - //as operator + + // collect api + def list = new File("src/main/resources/fileContent.txt").collect { it } + + // as operator def array = new File("src/main/resources/fileContent.txt") as String[] - - //eachline - new File("src/main/resources/fileContent.txt").eachLine { line -> - println line - } - + + // eachline + new File("src/main/resources/fileContent.txt").eachLine { println it } + //newInputStream with eachLine - def is = new File("src/main/resources/fileContent.txt").newInputStream() - is.eachLine { - println it + + // try-with-resources automatically closes BufferedInputStream resource + try (def inputStream = new File("src/main/resources/fileContent.txt").newInputStream()) { + inputStream.eachLine { println it } } - is.close() - - //withInputStream + + // withInputStream new File("src/main/resources/fileContent.txt").withInputStream { stream -> stream.eachLine { line -> println line } } } - -} \ No newline at end of file +} diff --git a/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/file/ReadFileUnitTest.groovy b/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/file/ReadFileUnitTest.groovy index da1dfc10ba..87cfc79761 100644 --- a/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/file/ReadFileUnitTest.groovy +++ b/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/file/ReadFileUnitTest.groovy @@ -1,71 +1,76 @@ package com.baeldung.file import spock.lang.Specification -import spock.lang.Ignore class ReadFileUnitTest extends Specification { ReadFile readFile - void setup () { + void setup() { readFile = new ReadFile() } - def 'Should return number of lines in File using ReadFile.readFileLineByLine given filePath' () { + def 'Should return number of lines in File using ReadFile.readFileLineByLine given filePath'() { given: - def filePath = "src/main/resources/fileContent.txt" + def filePath = "src/main/resources/fileContent.txt" + when: - def noOfLines = readFile.readFileLineByLine(filePath) + def noOfLines = readFile.readFileLineByLine(filePath) + then: - noOfLines - noOfLines instanceof Integer - assert noOfLines, 3 - } - - def 'Should return File Content in list of lines using ReadFile.readFileInList given filePath' () { - given: - def filePath = "src/main/resources/fileContent.txt" - when: - def lines = readFile.readFileInList(filePath) - then: - lines - lines instanceof List - assert lines.size(), 3 - } - - def 'Should return file content in string using ReadFile.readFileString given filePath' () { - given: - def filePath = "src/main/resources/fileContent.txt" - when: - def fileContent = readFile.readFileString(filePath) - then: - fileContent - fileContent instanceof String - fileContent.contains("""Line 1 : Hello World!!! -Line 2 : This is a file content. -Line 3 : String content""") - + noOfLines + noOfLines instanceof Integer + noOfLines == 3 } - def 'Should return UTF-8 encoded file content in string using ReadFile.readFileStringWithCharset given filePath' () { + def 'Should return File Content in list of lines using ReadFile.readFileInList given filePath'() { given: - def filePath = "src/main/resources/utf8Content.html" + def filePath = "src/main/resources/fileContent.txt" + when: - def encodedContent = readFile.readFileStringWithCharset(filePath) + def lines = readFile.readFileInList(filePath) + then: - encodedContent - encodedContent instanceof String + lines + lines instanceof List + lines.size() == 3 } - - def 'Should return binary file content in byte array using ReadFile.readBinaryFile given filePath' () { + + def 'Should return file content in string using ReadFile.readFileString given filePath'() { given: - def filePath = "src/main/resources/sample.png" + def filePath = "src/main/resources/fileContent.txt" + when: - def binaryContent = readFile.readBinaryFile(filePath) + def fileContent = readFile.readFileString(filePath) + then: - binaryContent - binaryContent instanceof byte[] - binaryContent.length == 329 + fileContent + fileContent instanceof String + fileContent.contains(["Line 1 : Hello World!!!", "Line 2 : This is a file content.", "Line 3 : String content"].join("\r\n")) } - -} \ No newline at end of file + + def 'Should return UTF-8 encoded file content in string using ReadFile.readFileStringWithCharset given filePath'() { + given: + def filePath = "src/main/resources/utf8Content.html" + + when: + def encodedContent = readFile.readFileStringWithCharset(filePath) + + then: + encodedContent + encodedContent instanceof String + } + + def 'Should return binary file content in byte array using ReadFile.readBinaryFile given filePath'() { + given: + def filePath = "src/main/resources/sample.png" + + when: + def binaryContent = readFile.readBinaryFile(filePath) + + then: + binaryContent + binaryContent instanceof byte[] + binaryContent.length == 329 + } +} From f2c9fbde810b3708557553c83bc5dda902a87059 Mon Sep 17 00:00:00 2001 From: Alex Golub Date: Sun, 15 Jan 2023 22:13:35 +0200 Subject: [PATCH 06/16] Minor fixes for Trait subject --- .../com/baeldung/traits/AnimalTrait.groovy | 4 +- .../groovy/com/baeldung/traits/Dog.groovy | 5 +- .../com/baeldung/traits/Employee.groovy | 6 +- .../groovy/com/baeldung/traits/Human.groovy | 4 +- .../com/baeldung/traits/SpeakingTrait.groovy | 7 +- .../com/baeldung/traits/UserTrait.groovy | 25 ++- .../com/baeldung/traits/VehicleTrait.groovy | 8 +- .../com/baeldung/traits/WalkingTrait.groovy | 8 +- .../com/baeldung/traits/WheelTrait.groovy | 5 +- .../com/baeldung/traits/TraitsUnitTest.groovy | 145 +++++++++--------- 10 files changed, 109 insertions(+), 108 deletions(-) diff --git a/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/AnimalTrait.groovy b/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/AnimalTrait.groovy index 6ec5cda571..a3fed81c8b 100644 --- a/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/AnimalTrait.groovy +++ b/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/AnimalTrait.groovy @@ -1,8 +1,8 @@ package com.baeldung.traits trait AnimalTrait { - + String basicBehavior() { return "Animalistic!!" } -} \ No newline at end of file +} diff --git a/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/Dog.groovy b/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/Dog.groovy index 3e0677ba18..fc53b1bef9 100644 --- a/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/Dog.groovy +++ b/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/Dog.groovy @@ -1,9 +1,8 @@ package com.baeldung.traits class Dog implements WalkingTrait, SpeakingTrait { - + String speakAndWalk() { WalkingTrait.super.speakAndWalk() } - -} \ No newline at end of file +} diff --git a/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/Employee.groovy b/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/Employee.groovy index b3e4285476..16f1fab984 100644 --- a/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/Employee.groovy +++ b/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/Employee.groovy @@ -1,12 +1,14 @@ package com.baeldung.traits class Employee implements UserTrait { - + + @Override String name() { return 'Bob' } + @Override String lastName() { return "Marley" } -} \ No newline at end of file +} diff --git a/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/Human.groovy b/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/Human.groovy index e78d59bbfd..5417334269 100644 --- a/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/Human.groovy +++ b/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/Human.groovy @@ -1,6 +1,6 @@ package com.baeldung.traits interface Human { - + String lastName() -} \ No newline at end of file +} diff --git a/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/SpeakingTrait.groovy b/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/SpeakingTrait.groovy index f437a94bd9..969982e8e0 100644 --- a/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/SpeakingTrait.groovy +++ b/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/SpeakingTrait.groovy @@ -1,13 +1,12 @@ package com.baeldung.traits trait SpeakingTrait { - + String basicAbility() { return "Speaking!!" } - + String speakAndWalk() { return "Speak and walk!!" } - -} \ No newline at end of file +} diff --git a/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/UserTrait.groovy b/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/UserTrait.groovy index 0d395bffcd..1d1d188460 100644 --- a/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/UserTrait.groovy +++ b/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/UserTrait.groovy @@ -1,36 +1,35 @@ package com.baeldung.traits trait UserTrait implements Human { - + + String email + String address + + abstract String name() + String sayHello() { return "Hello!" } - - abstract String name() - + String showName() { - return "Hello, ${name()}!" + return "Hello, ${name()}!" } private String greetingMessage() { return 'Hello, from a private method!' } - + String greet() { def msg = greetingMessage() println msg msg } - + def self() { - return this + return this } - + String showLastName() { return "Hello, ${lastName()}!" } - - String email - String address } - \ No newline at end of file diff --git a/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/VehicleTrait.groovy b/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/VehicleTrait.groovy index f5ae8fab30..e29561157c 100644 --- a/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/VehicleTrait.groovy +++ b/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/VehicleTrait.groovy @@ -1,9 +1,9 @@ package com.baeldung trait VehicleTrait extends WheelTrait { - + String showWheels() { - return "Num of Wheels $noOfWheels" + return "Num of Wheels $noOfWheels" } - -} \ No newline at end of file + +} diff --git a/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/WalkingTrait.groovy b/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/WalkingTrait.groovy index 66cff8809f..84be49ec25 100644 --- a/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/WalkingTrait.groovy +++ b/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/WalkingTrait.groovy @@ -1,13 +1,13 @@ package com.baeldung.traits trait WalkingTrait { - + String basicAbility() { return "Walking!!" } - + String speakAndWalk() { return "Walk and speak!!" } - -} \ No newline at end of file + +} diff --git a/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/WheelTrait.groovy b/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/WheelTrait.groovy index 364d5b883e..7f2448e185 100644 --- a/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/WheelTrait.groovy +++ b/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/WheelTrait.groovy @@ -1,7 +1,6 @@ package com.baeldung trait WheelTrait { - + int noOfWheels - -} \ No newline at end of file +} diff --git a/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/traits/TraitsUnitTest.groovy b/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/traits/TraitsUnitTest.groovy index 85130e8f07..b47cba6437 100644 --- a/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/traits/TraitsUnitTest.groovy +++ b/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/traits/TraitsUnitTest.groovy @@ -7,108 +7,111 @@ class TraitsUnitTest extends Specification { Employee employee Dog dog - void setup () { + void setup() { employee = new Employee() dog = new Dog() } - def 'Should return msg string when using Employee.sayHello method provided by UserTrait' () { + def 'Should return msg string when using Employee.sayHello method provided by UserTrait'() { when: - def msg = employee.sayHello() + def msg = employee.sayHello() + then: - msg - msg instanceof String - assert msg == "Hello!" + msg + msg instanceof String + msg == "Hello!" } - - def 'Should return displayMsg string when using Employee.showName method' () { + + def 'Should return displayMsg string when using Employee.showName method'() { when: - def displayMsg = employee.showName() + def displayMsg = employee.showName() + then: - displayMsg - displayMsg instanceof String - assert displayMsg == "Hello, Bob!" + displayMsg + displayMsg instanceof String + displayMsg == "Hello, Bob!" } - - def 'Should return greetMsg string when using Employee.greet method' () { + + def 'Should return greetMsg string when using Employee.greet method'() { when: - def greetMsg = employee.greet() + def greetMsg = employee.greet() + then: - greetMsg - greetMsg instanceof String - assert greetMsg == "Hello, from a private method!" + greetMsg + greetMsg instanceof String + greetMsg == "Hello, from a private method!" } - - def 'Should return MissingMethodException when using Employee.greetingMessage method' () { + + def 'Should return MissingMethodException when using Employee.greetingMessage method'() { when: - def exception - try { - employee.greetingMessage() - }catch(Exception e) { - exception = e - } - + employee.greetingMessage() + then: - exception - exception instanceof groovy.lang.MissingMethodException - assert exception.message == "No signature of method: com.baeldung.traits.Employee.greetingMessage()"+ - " is applicable for argument types: () values: []" + thrown(MissingMethodException) + specificationContext.thrownException.message == + "No signature of method: com.baeldung.traits.Employee.greetingMessage() is applicable for argument types: () values: []" } - - def 'Should return employee instance when using Employee.whoAmI method' () { + + def 'Should return employee instance when using Employee.whoAmI method'() { when: - def emp = employee.self() + def emp = employee.self() + then: - emp - emp instanceof Employee - assert emp.is(employee) + emp + emp instanceof Employee + emp.is(employee) } - - def 'Should display lastName when using Employee.showLastName method' () { + + def 'Should display lastName when using Employee.showLastName method'() { when: - def lastNameMsg = employee.showLastName() + def lastNameMsg = employee.showLastName() + then: - lastNameMsg - lastNameMsg instanceof String - assert lastNameMsg == "Hello, Marley!" + lastNameMsg + lastNameMsg instanceof String + lastNameMsg == "Hello, Marley!" } - - def 'Should be able to define properties of UserTrait in Employee instance' () { + + def 'Should be able to define properties of UserTrait in Employee instance'() { when: - employee = new Employee(email: "a@e.com", address: "baeldung.com") + employee = new Employee(email: "a@e.com", address: "baeldung.com") + then: - employee - employee instanceof Employee - assert employee.email == "a@e.com" - assert employee.address == "baeldung.com" + employee + employee instanceof Employee + employee.email == "a@e.com" + employee.address == "baeldung.com" } - - def 'Should execute basicAbility method from SpeakingTrait and return msg string' () { + + def 'Should execute basicAbility method from SpeakingTrait and return msg string'() { when: - def speakMsg = dog.basicAbility() + def speakMsg = dog.basicAbility() + then: - speakMsg - speakMsg instanceof String - assert speakMsg == "Speaking!!" + speakMsg + speakMsg instanceof String + speakMsg == "Speaking!!" } - - def 'Should verify multiple inheritance with traits and execute overridden traits method' () { + + def 'Should verify multiple inheritance with traits and execute overridden traits method'() { when: - def walkSpeakMsg = dog.speakAndWalk() - println walkSpeakMsg + def walkSpeakMsg = dog.speakAndWalk() + println walkSpeakMsg + then: - walkSpeakMsg - walkSpeakMsg instanceof String - assert walkSpeakMsg == "Walk and speak!!" + walkSpeakMsg + walkSpeakMsg instanceof String + walkSpeakMsg == "Walk and speak!!" } - - def 'Should implement AnimalTrait at runtime and access basicBehavior method' () { + + def 'Should implement AnimalTrait at runtime and access basicBehavior method'() { when: - def dogInstance = new Dog() as AnimalTrait - def basicBehaviorMsg = dogInstance.basicBehavior() + def dogInstance = new Dog() as AnimalTrait + def basicBehaviorMsg = dogInstance.basicBehavior() + then: - basicBehaviorMsg - basicBehaviorMsg instanceof String - assert basicBehaviorMsg == "Animalistic!!" + basicBehaviorMsg + basicBehaviorMsg instanceof String + basicBehaviorMsg == "Animalistic!!" } -} \ No newline at end of file +} From 3d36abe4f8d573b35ba6e6d4f024f69c8bb52745 Mon Sep 17 00:00:00 2001 From: Alex Golub Date: Sat, 14 Jan 2023 21:31:29 +0200 Subject: [PATCH 07/16] Align tests with `Spock` testing framework --- .../TemplateEnginesUnitTest.groovy | 115 ++++++++------ .../com/baeldung/strings/Concatenate.groovy | 24 ++- .../baeldung/strings/ConcatenateTest.groovy | 149 ++++++++---------- .../strings/StringMatchingSpec.groovy | 2 +- .../stringtoint/ConvertStringToInt.groovy | 131 ++++++++------- .../stringtypes/CharacterInGroovy.groovy | 17 +- .../stringtypes/DoubleQuotedString.groovy | 63 ++++---- .../stringtypes/SingleQuotedString.groovy | 15 +- .../com/baeldung/stringtypes/Strings.groovy | 21 +-- 9 files changed, 288 insertions(+), 249 deletions(-) diff --git a/core-groovy-modules/core-groovy-2/src/test/groovy/com/baeldung/templateengine/TemplateEnginesUnitTest.groovy b/core-groovy-modules/core-groovy-2/src/test/groovy/com/baeldung/templateengine/TemplateEnginesUnitTest.groovy index 1846ae664c..800f3b119e 100644 --- a/core-groovy-modules/core-groovy-2/src/test/groovy/com/baeldung/templateengine/TemplateEnginesUnitTest.groovy +++ b/core-groovy-modules/core-groovy-2/src/test/groovy/com/baeldung/templateengine/TemplateEnginesUnitTest.groovy @@ -1,48 +1,62 @@ package com.baeldung.templateengine +import groovy.text.GStringTemplateEngine import groovy.text.SimpleTemplateEngine import groovy.text.StreamingTemplateEngine -import groovy.text.GStringTemplateEngine -import groovy.text.XmlTemplateEngine import groovy.text.XmlTemplateEngine import groovy.text.markup.MarkupTemplateEngine import groovy.text.markup.TemplateConfiguration +import spock.lang.Specification -class TemplateEnginesUnitTest extends GroovyTestCase { - - def bindMap = [user: "Norman", signature: "Baeldung"] - - void testSimpleTemplateEngine() { +class TemplateEnginesUnitTest extends Specification { + + final Map BIND_MAP = [user: "Norman", signature: "Baeldung"] + + def "testSimpleTemplateEngine"() { + given: def smsTemplate = 'Dear <% print user %>, Thanks for reading our Article. ${signature}' - def smsText = new SimpleTemplateEngine().createTemplate(smsTemplate).make(bindMap) - assert smsText.toString() == "Dear Norman, Thanks for reading our Article. Baeldung" + when: + def smsText = new SimpleTemplateEngine().createTemplate(smsTemplate).make(BIND_MAP) + + then: + smsText.toString() == "Dear Norman, Thanks for reading our Article. Baeldung" } - - void testStreamingTemplateEngine() { + + def "testStreamingTemplateEngine"() { + given: def articleEmailTemplate = new File('src/main/resources/articleEmail.template') - bindMap.articleText = """1. Overview -This is a tutorial article on Template Engines""" //can be a string larger than 64k - - def articleEmailText = new StreamingTemplateEngine().createTemplate(articleEmailTemplate).make(bindMap) - - assert articleEmailText.toString() == """Dear Norman, -Please read the requested article below. -1. Overview -This is a tutorial article on Template Engines -From, -Baeldung""" - + //can be a string larger than 64k + BIND_MAP.articleText = """|1. Overview + |This is a tutorial article on Template Engines""".stripMargin() + + when: + def articleEmailText = new StreamingTemplateEngine().createTemplate(articleEmailTemplate).make(BIND_MAP) + + then: + articleEmailText.toString() == """|Dear Norman, + |Please read the requested article below. + |1. Overview + |This is a tutorial article on Template Engines + |From, + |Baeldung""".stripMargin() } - - void testGStringTemplateEngine() { + + def "testGStringTemplateEngine"() { + given: def emailTemplate = new File('src/main/resources/email.template') - def emailText = new GStringTemplateEngine().createTemplate(emailTemplate).make(bindMap) - - assert emailText.toString() == "Dear Norman,\nThanks for subscribing our services.\nBaeldung" + + when: + def emailText = new GStringTemplateEngine().createTemplate(emailTemplate).make(BIND_MAP) + + then: + emailText.toString() == """|Dear Norman, + |Thanks for subscribing our services. + |Baeldung""".stripMargin() } - - void testXmlTemplateEngine() { + + def "testXmlTemplateEngine"() { + given: def emailXmlTemplate = ''' def emailContent = "Thanks for subscribing our services." @@ -51,11 +65,16 @@ Baeldung""" ${signature} ''' - def emailXml = new XmlTemplateEngine().createTemplate(emailXmlTemplate).make(bindMap) + + when: + def emailXml = new XmlTemplateEngine().createTemplate(emailXmlTemplate).make(BIND_MAP) + + then: println emailXml.toString() } - - void testMarkupTemplateEngineHtml() { + + def "testMarkupTemplateEngineHtml"() { + given: def emailHtmlTemplate = """html { head { title('Service Subscription Email') @@ -66,14 +85,16 @@ Baeldung""" p('Baeldung') } }""" - - + + when: def emailHtml = new MarkupTemplateEngine().createTemplate(emailHtmlTemplate).make() + + then: println emailHtml.toString() - } - - void testMarkupTemplateEngineXml() { + + def "testMarkupTemplateEngineXml"() { + given: def emailXmlTemplate = """xmlDeclaration() xs{ email { @@ -83,14 +104,18 @@ Baeldung""" } } """ - TemplateConfiguration config = new TemplateConfiguration() - config.autoIndent = true - config.autoEscape = true - config.autoNewLine = true + TemplateConfiguration config = new TemplateConfiguration().with { + autoIndent = true + autoEscape = true + autoNewLine = true + return it + } + + when: def emailXml = new MarkupTemplateEngine(config).createTemplate(emailXmlTemplate).make() - + + then: println emailXml.toString() } - -} \ No newline at end of file +} diff --git a/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/strings/Concatenate.groovy b/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/strings/Concatenate.groovy index b3a0852a0b..4a7c3f8529 100644 --- a/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/strings/Concatenate.groovy +++ b/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/strings/Concatenate.groovy @@ -1,9 +1,10 @@ package com.baeldung.strings; class Concatenate { + String first = 'Hello' String last = 'Groovy' - + String doSimpleConcat() { return 'My name is ' + first + ' ' + last } @@ -23,21 +24,28 @@ class Concatenate { String doConcatUsingLeftShiftOperator() { return 'My name is ' << first << ' ' << last } - + String doConcatUsingArrayJoinMethod() { return ['My name is', first, last].join(' ') } String doConcatUsingArrayInjectMethod() { - return [first,' ', last] - .inject(new StringBuffer('My name is '), { initial, name -> initial.append(name); return initial }).toString() + return [first, ' ', last] + .inject(new StringBuffer('My name is '), { initial, name -> initial.append(name) }) + .toString() } - + String doConcatUsingStringBuilder() { - return new StringBuilder().append('My name is ').append(first).append(' ').append(last) + return new StringBuilder().append('My name is ') + .append(first) + .append(' ') + .append(last) } String doConcatUsingStringBuffer() { - return new StringBuffer().append('My name is ').append(first).append(' ').append(last) + return new StringBuffer().append('My name is ') + .append(first) + .append(' ') + .append(last) } -} \ No newline at end of file +} diff --git a/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/strings/ConcatenateTest.groovy b/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/strings/ConcatenateTest.groovy index 3ef4a5d460..e4a178a14b 100644 --- a/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/strings/ConcatenateTest.groovy +++ b/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/strings/ConcatenateTest.groovy @@ -1,101 +1,88 @@ -import com.baeldung.strings.Concatenate; +import com.baeldung.strings.Concatenate +import spock.lang.Specification -class ConcatenateTest extends GroovyTestCase { - - void testSimpleConcat() { - def name = new Concatenate() - name.first = 'Joe'; - name.last = 'Smith'; - def expected = 'My name is Joe Smith' - assertToString(name.doSimpleConcat(), expected) - } - - void testConcatUsingGString() { - def name = new Concatenate() - name.first = "Joe"; - name.last = "Smith"; - def expected = "My name is Joe Smith" - assertToString(name.doConcatUsingGString(), expected) - } - - void testConcatUsingGStringClosures() { - def name = new Concatenate() - name.first = "Joe"; - name.last = "Smith"; - def expected = "My name is Joe Smith" - assertToString(name.doConcatUsingGStringClosures(), expected) - } - - void testConcatUsingStringConcatMethod() { - def name = new Concatenate() - name.first = "Joe"; - name.last = "Smith"; - def expected = "My name is Joe Smith" - assertToString(name.doConcatUsingStringConcatMethod(), expected) +class ConcatenateTest extends Specification { + + final Concatenate NAME = new Concatenate(first: 'Joe', last: 'Smith') + final String EXPECTED = "My name is Joe Smith"; + + def "SimpleConcat"() { + expect: + NAME.doSimpleConcat() == EXPECTED } - void testConcatUsingLeftShiftOperator() { - def name = new Concatenate() - name.first = "Joe"; - name.last = "Smith"; - def expected = "My name is Joe Smith" - assertToString(name.doConcatUsingLeftShiftOperator(), expected) + def "ConcatUsingGString"() { + expect: + NAME.doConcatUsingGString() == EXPECTED } - void testConcatUsingArrayJoinMethod() { - def name = new Concatenate() - name.first = "Joe"; - name.last = "Smith"; - def expected = "My name is Joe Smith" - assertToString(name.doConcatUsingArrayJoinMethod(), expected) + def "ConcatUsingGStringClosures"() { + expect: + NAME.doConcatUsingGStringClosures() == EXPECTED } - void testConcatUsingArrayInjectMethod() { - def name = new Concatenate() - name.first = "Joe"; - name.last = "Smith"; - def expected = "My name is Joe Smith" - assertToString(name.doConcatUsingArrayInjectMethod(), expected) + def "ConcatUsingStringConcatMethod"() { + expect: + NAME.doConcatUsingStringConcatMethod() == EXPECTED } - void testConcatUsingStringBuilder() { - def name = new Concatenate() - name.first = "Joe"; - name.last = "Smith"; - def expected = "My name is Joe Smith" - assertToString(name.doConcatUsingStringBuilder(), expected) + def "ConcatUsingLeftShiftOperator"() { + expect: + NAME.doConcatUsingLeftShiftOperator() == EXPECTED } - void testConcatUsingStringBuffer() { - def name = new Concatenate() - name.first = "Joe"; - name.last = "Smith"; - def expected = "My name is Joe Smith" - assertToString(name.doConcatUsingStringBuffer(), expected) + def "ConcatUsingArrayJoinMethod"() { + expect: + NAME.doConcatUsingArrayJoinMethod() == EXPECTED } - void testConcatMultilineUsingStringConcatMethod() { - def name = new Concatenate() - name.first = '''Joe + def "ConcatUsingArrayInjectMethod"() { + expect: + NAME.doConcatUsingArrayInjectMethod() == EXPECTED + } + + def "ConcatUsingStringBuilder"() { + expect: + NAME.doConcatUsingStringBuilder() == EXPECTED + } + + def "ConcatUsingStringBuffer"() { + expect: + NAME.doConcatUsingStringBuffer() == EXPECTED + } + + def "ConcatMultilineUsingStringConcatMethod"() { + when: + NAME.first = '''Joe Smith - '''; - name.last = 'Junior'; + ''' + NAME.last = 'Junior' + + then: def expected = '''My name is Joe Smith - Junior'''; - assertToString(name.doConcatUsingStringConcatMethod(), expected) + Junior''' + NAME.doConcatUsingStringConcatMethod() == expected } - void testGStringvsClosure(){ - def first = "Joe"; - def last = "Smith"; - def eagerGString = "My name is $first $last" - def lazyGString = "My name is ${-> first} ${-> last}" + def "GStringvsClosure"() { + given: + def eagerGString = "My name is $NAME.first $NAME.last" + def lazyGString = "My name is ${-> NAME.first} ${-> NAME.last}" - assert eagerGString == "My name is Joe Smith" - assert lazyGString == "My name is Joe Smith" - first = "David"; - assert eagerGString == "My name is Joe Smith" - assert lazyGString == "My name is David Smith" - } + expect: + eagerGString == "My name is Joe Smith" + lazyGString == "My name is Joe Smith" + } + + def "LazyVsEager"() { + given: + def eagerGString = "My name is $NAME.first $NAME.last" + def lazyGString = "My name is ${-> NAME.first} ${-> NAME.last}" + NAME.first = "David" + + expect: + eagerGString == "My name is Joe Smith" + lazyGString == "My name is David Smith" + } } diff --git a/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/strings/StringMatchingSpec.groovy b/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/strings/StringMatchingSpec.groovy index 3865bc73fa..89202d9500 100644 --- a/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/strings/StringMatchingSpec.groovy +++ b/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/strings/StringMatchingSpec.groovy @@ -13,7 +13,7 @@ class StringMatchingSpec extends Specification { expect: p instanceof Pattern - and: "you can use slash strings to avoid escaping of blackslash" + and: "you can use slash strings to avoid escaping of backslash" def digitPattern = ~/\d*/ digitPattern.matcher('4711').matches() } diff --git a/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/stringtoint/ConvertStringToInt.groovy b/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/stringtoint/ConvertStringToInt.groovy index 48cf48fa8a..cce6ede989 100644 --- a/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/stringtoint/ConvertStringToInt.groovy +++ b/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/stringtoint/ConvertStringToInt.groovy @@ -1,110 +1,119 @@ package com.baeldung.stringtoint -import org.junit.Test +import spock.lang.Specification import java.text.DecimalFormat -import static org.junit.Assert.assertEquals -import static org.junit.Assert.assertNull +class ConvertStringToInt extends Specification { -class ConvertStringToInt { + final String STRING_NUM = "123" + final int EXPECTED_INT = 123 - @Test - void givenString_whenUsingAsInteger_thenConvertToInteger() { - def stringNum = "123" + def "givenString_whenUsingAsInteger_thenConvertToInteger"() { + given: def invalidString = "123a" - Integer expectedInteger = 123 - Integer integerNum = stringNum as Integer + Integer integerNum = STRING_NUM as Integer + + when: def intNum = invalidString?.isInteger() ? invalidString as Integer : null - assertNull(null, intNum) - assertEquals(integerNum, expectedInteger) + then: + intNum == null + integerNum == EXPECTED_INT } - @Test - void givenString_whenUsingAsInt_thenConvertToInt() { - def stringNum = "123" - int expectedInt = 123 - int intNum = stringNum as int + def "givenString_whenUsingAsInt_thenConvertToInt"() { + given: + int intNum = STRING_NUM as int - assertEquals(intNum, expectedInt) + expect: + intNum == EXPECTED_INT } - @Test - void givenString_whenUsingToInteger_thenConvertToInteger() { - def stringNum = "123" - int expectedInt = 123 - int intNum = stringNum.toInteger() + def "givenString_whenUsingToInteger_thenConvertToInteger"() { + given: + int intNum = STRING_NUM.toInteger() - assertEquals(intNum, expectedInt) + expect: + intNum == EXPECTED_INT } - @Test - void givenString_whenUsingParseInt_thenConvertToInteger() { - def stringNum = "123" - int expectedInt = 123 - int intNum = Integer.parseInt(stringNum) + def "givenString_whenUsingParseInt_thenConvertToInteger"() { + given: + int intNum = Integer.parseInt(STRING_NUM) - assertEquals(intNum, expectedInt) + expect: + intNum == EXPECTED_INT } - @Test - void givenString_whenUsingValueOf_thenConvertToInteger() { - def stringNum = "123" - int expectedInt = 123 - int intNum = Integer.valueOf(stringNum) + def "givenString_whenUsingValueOf_thenConvertToInteger"() { + given: + int intNum = Integer.valueOf(STRING_NUM) - assertEquals(intNum, expectedInt) + expect: + intNum == EXPECTED_INT } - @Test - void givenString_whenUsingIntValue_thenConvertToInteger() { - def stringNum = "123" - int expectedInt = 123 - int intNum = new Integer(stringNum).intValue() + def "givenString_whenUsingIntValue_thenConvertToInteger"() { + given: + int intNum = Integer.valueOf(STRING_NUM).intValue() - assertEquals(intNum, expectedInt) + expect: + intNum == EXPECTED_INT } - @Test - void givenString_whenUsingNewInteger_thenConvertToInteger() { - def stringNum = "123" - int expectedInt = 123 - int intNum = new Integer(stringNum) + def "givenString_whenUsingNewInteger_thenConvertToInteger"() { + given: + Integer intNum = Integer.valueOf(STRING_NUM) - assertEquals(intNum, expectedInt) + expect: + intNum == EXPECTED_INT } - @Test - void givenString_whenUsingDecimalFormat_thenConvertToInteger() { - def stringNum = "123" - int expectedInt = 123 + def "givenString_whenUsingDecimalFormat_thenConvertToInteger"() { + given: DecimalFormat decimalFormat = new DecimalFormat("#") - int intNum = decimalFormat.parse(stringNum).intValue() - assertEquals(intNum, expectedInt) + when: + int intNum = decimalFormat.parse(STRING_NUM).intValue() + + then: + intNum == EXPECTED_INT } - @Test(expected = NumberFormatException.class) - void givenInvalidString_whenUsingAs_thenThrowNumberFormatException() { + def "givenInvalidString_whenUsingAs_thenThrowNumberFormatException"() { + given: def invalidString = "123a" + + when: invalidString as Integer + + then: + thrown(NumberFormatException) } - @Test(expected = NullPointerException.class) - void givenNullString_whenUsingToInteger_thenThrowNullPointerException() { + def "givenNullString_whenUsingToInteger_thenThrowNullPointerException"() { + given: def invalidString = null + + when: invalidString.toInteger() + + then: + thrown(NullPointerException) } - @Test - void givenString_whenUsingIsInteger_thenCheckIfCorrectValue() { + def "givenString_whenUsingIsInteger_thenCheckIfCorrectValue"() { + given: def invalidString = "123a" def validString = "123" + + when: def invalidNum = invalidString?.isInteger() ? invalidString as Integer : false def correctNum = validString?.isInteger() ? validString as Integer : false - assertEquals(false, invalidNum) - assertEquals(123, correctNum) + then: + !invalidNum + correctNum == 123 } } diff --git a/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/stringtypes/CharacterInGroovy.groovy b/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/stringtypes/CharacterInGroovy.groovy index c043723d95..30365ec9d7 100644 --- a/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/stringtypes/CharacterInGroovy.groovy +++ b/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/stringtypes/CharacterInGroovy.groovy @@ -1,19 +1,18 @@ package groovy.com.baeldung.stringtypes -import org.junit.Assert -import org.junit.Test +import spock.lang.Specification -class CharacterInGroovy { +class CharacterInGroovy extends Specification { - @Test - void 'character'() { + def 'character'() { + given: char a = 'A' as char char b = 'B' as char char c = (char) 'C' - Assert.assertTrue(a instanceof Character) - Assert.assertTrue(b instanceof Character) - Assert.assertTrue(c instanceof Character) + expect: + a instanceof Character + b instanceof Character + c instanceof Character } - } diff --git a/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/stringtypes/DoubleQuotedString.groovy b/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/stringtypes/DoubleQuotedString.groovy index a730244d0a..e1074145f4 100644 --- a/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/stringtypes/DoubleQuotedString.groovy +++ b/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/stringtypes/DoubleQuotedString.groovy @@ -1,67 +1,76 @@ package groovy.com.baeldung.stringtypes -import org.junit.Assert -import org.junit.Test +import spock.lang.Specification -class DoubleQuotedString { +class DoubleQuotedString extends Specification { - @Test - void 'escape double quoted string'() { + def 'escape double quoted string'() { + given: def example = "Hello \"world\"!" - println(example) + expect: + example == 'Hello "world"!' } - @Test - void 'String ang GString'() { + def 'String ang GString'() { + given: def string = "example" def stringWithExpression = "example${2}" - Assert.assertTrue(string instanceof String) - Assert.assertTrue(stringWithExpression instanceof GString) - Assert.assertTrue(stringWithExpression.toString() instanceof String) + expect: + string instanceof String + stringWithExpression instanceof GString + stringWithExpression.toString() instanceof String } - @Test - void 'placeholder with variable'() { + def 'placeholder with variable'() { + given: def name = "John" + + when: def helloName = "Hello $name!".toString() - Assert.assertEquals("Hello John!", helloName) + then: + helloName == "Hello John!" } - @Test - void 'placeholder with expression'() { + def 'placeholder with expression'() { + given: def result = "result is ${2 * 2}".toString() - Assert.assertEquals("result is 4", result) + expect: + result == "result is 4" } - @Test - void 'placeholder with dotted access'() { + def 'placeholder with dotted access'() { + given: def person = [name: 'John'] + when: def myNameIs = "I'm $person.name, and you?".toString() - Assert.assertEquals("I'm John, and you?", myNameIs) + then: + myNameIs == "I'm John, and you?" } - @Test - void 'placeholder with method call'() { + def 'placeholder with method call'() { + given: def name = 'John' + when: def result = "Uppercase name: ${name.toUpperCase()}".toString() - Assert.assertEquals("Uppercase name: JOHN", result) + then: + result == "Uppercase name: JOHN" } - @Test - void 'GString and String hashcode'() { + def 'GString and String hashcode'() { + given: def string = "2+2 is 4" def gstring = "2+2 is ${4}" - Assert.assertTrue(string.hashCode() != gstring.hashCode()) + expect: + string.hashCode() != gstring.hashCode() } - } diff --git a/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/stringtypes/SingleQuotedString.groovy b/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/stringtypes/SingleQuotedString.groovy index 569991b788..924515570c 100644 --- a/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/stringtypes/SingleQuotedString.groovy +++ b/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/stringtypes/SingleQuotedString.groovy @@ -1,15 +1,14 @@ package groovy.com.baeldung.stringtypes -import org.junit.Assert -import org.junit.Test +import spock.lang.Specification -class SingleQuotedString { +class SingleQuotedString extends Specification { - @Test - void 'single quoted string'() { - def example = 'Hello world' + def 'single quoted string'() { + given: + def example = 'Hello world!' - Assert.assertEquals('Hello world!', 'Hello' + ' world!') + expect: + example == 'Hello' + ' world!' } - } diff --git a/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/stringtypes/Strings.groovy b/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/stringtypes/Strings.groovy index e45f352285..9d29210d81 100644 --- a/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/stringtypes/Strings.groovy +++ b/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/stringtypes/Strings.groovy @@ -1,26 +1,29 @@ package groovy.com.baeldung.stringtypes -import org.junit.Assert -import org.junit.Test +import spock.lang.Specification -class Strings { +class Strings extends Specification { - @Test - void 'string interpolation '() { + def 'string interpolation '() { + given: def name = "Kacper" + when: def result = "Hello ${name}!" - Assert.assertEquals("Hello Kacper!", result.toString()) + then: + result.toString() == "Hello Kacper!" } - @Test - void 'string concatenation'() { + def 'string concatenation'() { + given: def first = "first" def second = "second" + when: def concatenation = first + second - Assert.assertEquals("firstsecond", concatenation) + then: + concatenation == "firstsecond" } } From d2eb17077fb30cd5123cd243e95b73e5b5d06b88 Mon Sep 17 00:00:00 2001 From: Alex Golub Date: Sun, 15 Jan 2023 22:13:35 +0200 Subject: [PATCH 08/16] Minor fixes for Trait subject --- .../com/baeldung/traits/AnimalTrait.groovy | 4 +- .../groovy/com/baeldung/traits/Dog.groovy | 5 +- .../com/baeldung/traits/Employee.groovy | 6 +- .../groovy/com/baeldung/traits/Human.groovy | 4 +- .../com/baeldung/traits/SpeakingTrait.groovy | 7 +- .../com/baeldung/traits/UserTrait.groovy | 25 ++- .../com/baeldung/traits/VehicleTrait.groovy | 8 +- .../com/baeldung/traits/WalkingTrait.groovy | 8 +- .../com/baeldung/traits/WheelTrait.groovy | 5 +- .../com/baeldung/traits/TraitsUnitTest.groovy | 145 +++++++++--------- 10 files changed, 109 insertions(+), 108 deletions(-) diff --git a/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/AnimalTrait.groovy b/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/AnimalTrait.groovy index 6ec5cda571..a3fed81c8b 100644 --- a/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/AnimalTrait.groovy +++ b/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/AnimalTrait.groovy @@ -1,8 +1,8 @@ package com.baeldung.traits trait AnimalTrait { - + String basicBehavior() { return "Animalistic!!" } -} \ No newline at end of file +} diff --git a/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/Dog.groovy b/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/Dog.groovy index 3e0677ba18..fc53b1bef9 100644 --- a/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/Dog.groovy +++ b/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/Dog.groovy @@ -1,9 +1,8 @@ package com.baeldung.traits class Dog implements WalkingTrait, SpeakingTrait { - + String speakAndWalk() { WalkingTrait.super.speakAndWalk() } - -} \ No newline at end of file +} diff --git a/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/Employee.groovy b/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/Employee.groovy index b3e4285476..16f1fab984 100644 --- a/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/Employee.groovy +++ b/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/Employee.groovy @@ -1,12 +1,14 @@ package com.baeldung.traits class Employee implements UserTrait { - + + @Override String name() { return 'Bob' } + @Override String lastName() { return "Marley" } -} \ No newline at end of file +} diff --git a/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/Human.groovy b/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/Human.groovy index e78d59bbfd..5417334269 100644 --- a/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/Human.groovy +++ b/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/Human.groovy @@ -1,6 +1,6 @@ package com.baeldung.traits interface Human { - + String lastName() -} \ No newline at end of file +} diff --git a/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/SpeakingTrait.groovy b/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/SpeakingTrait.groovy index f437a94bd9..969982e8e0 100644 --- a/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/SpeakingTrait.groovy +++ b/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/SpeakingTrait.groovy @@ -1,13 +1,12 @@ package com.baeldung.traits trait SpeakingTrait { - + String basicAbility() { return "Speaking!!" } - + String speakAndWalk() { return "Speak and walk!!" } - -} \ No newline at end of file +} diff --git a/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/UserTrait.groovy b/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/UserTrait.groovy index 0d395bffcd..1d1d188460 100644 --- a/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/UserTrait.groovy +++ b/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/UserTrait.groovy @@ -1,36 +1,35 @@ package com.baeldung.traits trait UserTrait implements Human { - + + String email + String address + + abstract String name() + String sayHello() { return "Hello!" } - - abstract String name() - + String showName() { - return "Hello, ${name()}!" + return "Hello, ${name()}!" } private String greetingMessage() { return 'Hello, from a private method!' } - + String greet() { def msg = greetingMessage() println msg msg } - + def self() { - return this + return this } - + String showLastName() { return "Hello, ${lastName()}!" } - - String email - String address } - \ No newline at end of file diff --git a/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/VehicleTrait.groovy b/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/VehicleTrait.groovy index f5ae8fab30..e29561157c 100644 --- a/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/VehicleTrait.groovy +++ b/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/VehicleTrait.groovy @@ -1,9 +1,9 @@ package com.baeldung trait VehicleTrait extends WheelTrait { - + String showWheels() { - return "Num of Wheels $noOfWheels" + return "Num of Wheels $noOfWheels" } - -} \ No newline at end of file + +} diff --git a/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/WalkingTrait.groovy b/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/WalkingTrait.groovy index 66cff8809f..84be49ec25 100644 --- a/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/WalkingTrait.groovy +++ b/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/WalkingTrait.groovy @@ -1,13 +1,13 @@ package com.baeldung.traits trait WalkingTrait { - + String basicAbility() { return "Walking!!" } - + String speakAndWalk() { return "Walk and speak!!" } - -} \ No newline at end of file + +} diff --git a/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/WheelTrait.groovy b/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/WheelTrait.groovy index 364d5b883e..7f2448e185 100644 --- a/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/WheelTrait.groovy +++ b/core-groovy-modules/core-groovy/src/main/groovy/com/baeldung/traits/WheelTrait.groovy @@ -1,7 +1,6 @@ package com.baeldung trait WheelTrait { - + int noOfWheels - -} \ No newline at end of file +} diff --git a/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/traits/TraitsUnitTest.groovy b/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/traits/TraitsUnitTest.groovy index 85130e8f07..b47cba6437 100644 --- a/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/traits/TraitsUnitTest.groovy +++ b/core-groovy-modules/core-groovy/src/test/groovy/com/baeldung/traits/TraitsUnitTest.groovy @@ -7,108 +7,111 @@ class TraitsUnitTest extends Specification { Employee employee Dog dog - void setup () { + void setup() { employee = new Employee() dog = new Dog() } - def 'Should return msg string when using Employee.sayHello method provided by UserTrait' () { + def 'Should return msg string when using Employee.sayHello method provided by UserTrait'() { when: - def msg = employee.sayHello() + def msg = employee.sayHello() + then: - msg - msg instanceof String - assert msg == "Hello!" + msg + msg instanceof String + msg == "Hello!" } - - def 'Should return displayMsg string when using Employee.showName method' () { + + def 'Should return displayMsg string when using Employee.showName method'() { when: - def displayMsg = employee.showName() + def displayMsg = employee.showName() + then: - displayMsg - displayMsg instanceof String - assert displayMsg == "Hello, Bob!" + displayMsg + displayMsg instanceof String + displayMsg == "Hello, Bob!" } - - def 'Should return greetMsg string when using Employee.greet method' () { + + def 'Should return greetMsg string when using Employee.greet method'() { when: - def greetMsg = employee.greet() + def greetMsg = employee.greet() + then: - greetMsg - greetMsg instanceof String - assert greetMsg == "Hello, from a private method!" + greetMsg + greetMsg instanceof String + greetMsg == "Hello, from a private method!" } - - def 'Should return MissingMethodException when using Employee.greetingMessage method' () { + + def 'Should return MissingMethodException when using Employee.greetingMessage method'() { when: - def exception - try { - employee.greetingMessage() - }catch(Exception e) { - exception = e - } - + employee.greetingMessage() + then: - exception - exception instanceof groovy.lang.MissingMethodException - assert exception.message == "No signature of method: com.baeldung.traits.Employee.greetingMessage()"+ - " is applicable for argument types: () values: []" + thrown(MissingMethodException) + specificationContext.thrownException.message == + "No signature of method: com.baeldung.traits.Employee.greetingMessage() is applicable for argument types: () values: []" } - - def 'Should return employee instance when using Employee.whoAmI method' () { + + def 'Should return employee instance when using Employee.whoAmI method'() { when: - def emp = employee.self() + def emp = employee.self() + then: - emp - emp instanceof Employee - assert emp.is(employee) + emp + emp instanceof Employee + emp.is(employee) } - - def 'Should display lastName when using Employee.showLastName method' () { + + def 'Should display lastName when using Employee.showLastName method'() { when: - def lastNameMsg = employee.showLastName() + def lastNameMsg = employee.showLastName() + then: - lastNameMsg - lastNameMsg instanceof String - assert lastNameMsg == "Hello, Marley!" + lastNameMsg + lastNameMsg instanceof String + lastNameMsg == "Hello, Marley!" } - - def 'Should be able to define properties of UserTrait in Employee instance' () { + + def 'Should be able to define properties of UserTrait in Employee instance'() { when: - employee = new Employee(email: "a@e.com", address: "baeldung.com") + employee = new Employee(email: "a@e.com", address: "baeldung.com") + then: - employee - employee instanceof Employee - assert employee.email == "a@e.com" - assert employee.address == "baeldung.com" + employee + employee instanceof Employee + employee.email == "a@e.com" + employee.address == "baeldung.com" } - - def 'Should execute basicAbility method from SpeakingTrait and return msg string' () { + + def 'Should execute basicAbility method from SpeakingTrait and return msg string'() { when: - def speakMsg = dog.basicAbility() + def speakMsg = dog.basicAbility() + then: - speakMsg - speakMsg instanceof String - assert speakMsg == "Speaking!!" + speakMsg + speakMsg instanceof String + speakMsg == "Speaking!!" } - - def 'Should verify multiple inheritance with traits and execute overridden traits method' () { + + def 'Should verify multiple inheritance with traits and execute overridden traits method'() { when: - def walkSpeakMsg = dog.speakAndWalk() - println walkSpeakMsg + def walkSpeakMsg = dog.speakAndWalk() + println walkSpeakMsg + then: - walkSpeakMsg - walkSpeakMsg instanceof String - assert walkSpeakMsg == "Walk and speak!!" + walkSpeakMsg + walkSpeakMsg instanceof String + walkSpeakMsg == "Walk and speak!!" } - - def 'Should implement AnimalTrait at runtime and access basicBehavior method' () { + + def 'Should implement AnimalTrait at runtime and access basicBehavior method'() { when: - def dogInstance = new Dog() as AnimalTrait - def basicBehaviorMsg = dogInstance.basicBehavior() + def dogInstance = new Dog() as AnimalTrait + def basicBehaviorMsg = dogInstance.basicBehavior() + then: - basicBehaviorMsg - basicBehaviorMsg instanceof String - assert basicBehaviorMsg == "Animalistic!!" + basicBehaviorMsg + basicBehaviorMsg instanceof String + basicBehaviorMsg == "Animalistic!!" } -} \ No newline at end of file +} From c333a3f3596c7675ff8a732a83412fc839d47416 Mon Sep 17 00:00:00 2001 From: Alex Golub Date: Wed, 18 Jan 2023 22:04:08 +0200 Subject: [PATCH 09/16] Data Type in Groovy: align with `Spock` testing framework --- .../baeldung/determinedatatype/Person.groovy | 23 ++-- .../determinedatatype/PersonTest.groovy | 104 ++++++++++-------- 2 files changed, 72 insertions(+), 55 deletions(-) diff --git a/core-groovy-modules/core-groovy-2/src/main/groovy/com/baeldung/determinedatatype/Person.groovy b/core-groovy-modules/core-groovy-2/src/main/groovy/com/baeldung/determinedatatype/Person.groovy index 3ac88b7952..40c935ce08 100644 --- a/core-groovy-modules/core-groovy-2/src/main/groovy/com/baeldung/determinedatatype/Person.groovy +++ b/core-groovy-modules/core-groovy-2/src/main/groovy/com/baeldung/determinedatatype/Person.groovy @@ -1,14 +1,19 @@ package com.baeldung.determinedatatype class Person { - - private int ageAsInt - private Double ageAsDouble - private String ageAsString - + + int ageAsInt + Double ageAsDouble + String ageAsString + Person() {} - Person(int ageAsInt) { this.ageAsInt = ageAsInt} - Person(Double ageAsDouble) { this.ageAsDouble = ageAsDouble} - Person(String ageAsString) { this.ageAsString = ageAsString} + + Person(int ageAsInt) { this.ageAsInt = ageAsInt } + + Person(Double ageAsDouble) { this.ageAsDouble = ageAsDouble } + + Person(String ageAsString) { this.ageAsString = ageAsString } +} + +class Student extends Person { } -class Student extends Person {} diff --git a/core-groovy-modules/core-groovy-2/src/test/groovy/com/baeldung/determinedatatype/PersonTest.groovy b/core-groovy-modules/core-groovy-2/src/test/groovy/com/baeldung/determinedatatype/PersonTest.groovy index 4c6589f207..414ba52fc5 100644 --- a/core-groovy-modules/core-groovy-2/src/test/groovy/com/baeldung/determinedatatype/PersonTest.groovy +++ b/core-groovy-modules/core-groovy-2/src/test/groovy/com/baeldung/determinedatatype/PersonTest.groovy @@ -1,56 +1,68 @@ package com.baeldung.determinedatatype -import org.junit.Assert -import org.junit.Test -import com.baeldung.determinedatatype.Person +import spock.lang.Specification -public class PersonTest { - - @Test - public void givenWhenParameterTypeIsInteger_thenReturnTrue() { +class PersonTest extends Specification { + + def "givenWhenParameterTypeIsIntegerThenReturnTrue"() { + given: Person personObj = new Person(10) - Assert.assertTrue(personObj.ageAsInt instanceof Integer) - } - - @Test - public void givenWhenParameterTypeIsDouble_thenReturnTrue() { - Person personObj = new Person(10.0) - Assert.assertTrue((personObj.ageAsDouble).getClass() == Double) - } - - @Test - public void givenWhenParameterTypeIsString_thenReturnTrue() { - Person personObj = new Person("10 years") - Assert.assertTrue(personObj.ageAsString.class == String) - } - - @Test - public void givenClassName_WhenParameterIsInteger_thenReturnTrue() { - Assert.assertTrue(Person.class.getDeclaredField('ageAsInt').type == int.class) - } - - @Test - public void givenWhenObjectIsInstanceOfType_thenReturnTrue() { - Person personObj = new Person() - Assert.assertTrue(personObj instanceof Person) + + expect: + personObj.ageAsInt.class == Integer } - @Test - public void givenWhenInstanceIsOfSubtype_thenReturnTrue() { + def "givenWhenParameterTypeIsDouble_thenReturnTrue"() { + given: + Person personObj = new Person(10.0) + + expect: + personObj.ageAsDouble.class == Double + } + + def "givenWhenParameterTypeIsString_thenReturnTrue"() { + given: + Person personObj = new Person("10 years") + + expect: + personObj.ageAsString.class == String + } + + def "givenClassName_WhenParameterIsInteger_thenReturnTrue"() { + expect: + Person.class.getDeclaredField('ageAsInt').type == int.class + } + + def "givenWhenObjectIsInstanceOfType_thenReturnTrue"() { + given: + Person personObj = new Person() + + expect: + personObj.class == Person + } + + def "givenWhenInstanceIsOfSubtype_thenReturnTrue"() { + given: Student studentObj = new Student() - Assert.assertTrue(studentObj in Person) + + expect: + studentObj.class.superclass == Person } - - @Test - public void givenGroovyList_WhenFindClassName_thenReturnTrue() { - def ageList = ['ageAsString','ageAsDouble', 10] - Assert.assertTrue(ageList.class == ArrayList) - Assert.assertTrue(ageList.getClass() == ArrayList) + + def "givenGroovyList_WhenFindClassName_thenReturnTrue"() { + given: + def ageList = ['ageAsString', 'ageAsDouble', 10] + + expect: + ageList.class == ArrayList + ageList.getClass() == ArrayList } - - @Test - public void givenGrooyMap_WhenFindClassName_thenReturnTrue() { - def ageMap = [ageAsString: '10 years', ageAsDouble: 10.0] - Assert.assertFalse(ageMap.class == LinkedHashMap) + + def "givenGroovyMap_WhenFindClassName_thenReturnTrue"() { + given: + def ageMap = [ageAsString: '10 years', ageAsDouble: 10.0] + + expect: + ageMap.getClass() == LinkedHashMap } -} \ No newline at end of file +} From 34c282de3425ce02ee627200de81268234e47c08 Mon Sep 17 00:00:00 2001 From: Alex Golub Date: Fri, 20 Jan 2023 12:28:29 +0200 Subject: [PATCH 10/16] Metaprogramming: Align with groovy version `3.0.8` and use spock testing framework --- .../baeldung/metaprogramming/Employee.groovy | 25 ++- .../extension/BasicExtensions.groovy | 19 +- .../MetaprogrammingUnitTest.groovy | 164 +++++++++++------- 3 files changed, 121 insertions(+), 87 deletions(-) diff --git a/core-groovy-modules/core-groovy-2/src/main/groovy/com/baeldung/metaprogramming/Employee.groovy b/core-groovy-modules/core-groovy-2/src/main/groovy/com/baeldung/metaprogramming/Employee.groovy index f49d0f906b..cade7dab3c 100644 --- a/core-groovy-modules/core-groovy-2/src/main/groovy/com/baeldung/metaprogramming/Employee.groovy +++ b/core-groovy-modules/core-groovy-2/src/main/groovy/com/baeldung/metaprogramming/Employee.groovy @@ -1,18 +1,14 @@ package com.baeldung.metaprogramming -import groovy.transform.AutoClone -import groovy.transform.Canonical -import groovy.transform.EqualsAndHashCode -import groovy.transform.ToString -import groovy.transform.TupleConstructor -import groovy.util.logging.* +import groovy.transform.* +import groovy.util.logging.Log -@Canonical +@ToString(includePackage = false, excludes = ['id']) @TupleConstructor @EqualsAndHashCode -@ToString(includePackage=false, excludes=['id']) -@Log -@AutoClone +@Canonical +@AutoClone(style = AutoCloneStyle.SIMPLE) +@Log class Employee { long id @@ -30,16 +26,15 @@ class Employee { def propertyMissing(String propertyName, propertyValue) { println "property '$propertyName' is not available" log.info "$propertyName is not available" - "property '$propertyName' is not available" + "property '$propertyName' with value '$propertyValue' is not available" } - def methodMissing(String methodName, def methodArgs) { + def methodMissing(String methodName, Object methodArgs) { log.info "$methodName is not defined" "method '$methodName' is not defined" } - + def logEmp() { log.info "Employee: $lastName, $firstName is of $age years age" } - -} \ No newline at end of file +} diff --git a/core-groovy-modules/core-groovy-2/src/main/groovy/com/baeldung/metaprogramming/extension/BasicExtensions.groovy b/core-groovy-modules/core-groovy-2/src/main/groovy/com/baeldung/metaprogramming/extension/BasicExtensions.groovy index 0612ecb955..7e9f0111cd 100644 --- a/core-groovy-modules/core-groovy-2/src/main/groovy/com/baeldung/metaprogramming/extension/BasicExtensions.groovy +++ b/core-groovy-modules/core-groovy-2/src/main/groovy/com/baeldung/metaprogramming/extension/BasicExtensions.groovy @@ -2,32 +2,31 @@ package com.baeldung.metaprogramming.extension import com.baeldung.metaprogramming.Employee -import java.time.LocalDate import java.time.Year class BasicExtensions { - + static int getYearOfBirth(Employee self) { return Year.now().value - self.age } - + static String capitalize(String self) { return self.substring(0, 1).toUpperCase() + self.substring(1) } static void printCounter(Integer self) { - while (self>0) { + while (self > 0) { println self self-- } } - + static Long square(Long self) { - return self*self + return self * self } - + static BigDecimal cube(BigDecimal self) { - return self*self*self + return self * self * self } - -} \ No newline at end of file + +} diff --git a/core-groovy-modules/core-groovy-2/src/test/groovy/com/baeldung/metaprogramming/MetaprogrammingUnitTest.groovy b/core-groovy-modules/core-groovy-2/src/test/groovy/com/baeldung/metaprogramming/MetaprogrammingUnitTest.groovy index 4a8631eb95..6959c97533 100644 --- a/core-groovy-modules/core-groovy-2/src/test/groovy/com/baeldung/metaprogramming/MetaprogrammingUnitTest.groovy +++ b/core-groovy-modules/core-groovy-2/src/test/groovy/com/baeldung/metaprogramming/MetaprogrammingUnitTest.groovy @@ -1,123 +1,163 @@ package com.baeldung.metaprogramming +import spock.lang.Specification -import java.time.LocalDate -import java.time.Period import java.time.Year -class MetaprogrammingUnitTest extends GroovyTestCase { +class MetaprogrammingUnitTest extends Specification { - Employee emp = new Employee(firstName: "Norman", lastName: "Lewis") + Employee emp - void testPropertyMissing() { - assert emp.address == "property 'address' is not available" + void setup() { + emp = new Employee(firstName: "Norman", lastName: "Lewis") } - void testMethodMissing() { + def "testPropertyMissing"() { + expect: + emp.address == "property 'address' is not available" + } + + def "testMethodMissing"() { + given: Employee emp = new Employee() - try { - emp.getFullName() - } catch(MissingMethodException e) { - println "method is not defined" - } - assert emp.getFullName() == "method 'getFullName' is not defined" + + expect: + emp.getFullName() == "method 'getFullName' is not defined" } - void testMetaClassProperty() { + def "testMetaClassProperty"() { + when: Employee.metaClass.address = "" - emp = new Employee(firstName: "Norman", lastName: "Lewis", address: "US") - assert emp.address == "US" + + and: + emp = new Employee(firstName: "Norman", + lastName: "Lewis", + address: "US") + + then: + emp.address == "US" } - void testMetaClassMethod() { + def "testMetaClassMethod"() { + when: emp.metaClass.getFullName = { "$lastName, $firstName" } - assert emp.getFullName() == "Lewis, Norman" + + then: + emp.getFullName() == "Lewis, Norman" } - void testMetaClassConstructor() { - try { - Employee emp = new Employee("Norman") - } catch(GroovyRuntimeException e) { - assert e.message == "Could not find matching constructor for: com.baeldung.metaprogramming.Employee(String)" - } + def "testOnlyNameConstructor"() { + when: + new Employee("Norman") + then: + thrown(GroovyRuntimeException) + } + + def "testMetaClassConstructor"() { + when: Employee.metaClass.constructor = { String firstName -> new Employee(firstName: firstName) } + and: Employee norman = new Employee("Norman") - assert norman.firstName == "Norman" - assert norman.lastName == null + + then: + norman.firstName == "Norman" + norman.lastName == null } - void testJavaMetaClass() { + def "testJavaMetaClass"() { + when: String.metaClass.capitalize = { String str -> str.substring(0, 1).toUpperCase() + str.substring(1) } - assert "norman".capitalize() == "Norman" + + and: + String.metaClass.static.joinWith = { String delimiter, String... args -> + String.join(delimiter, args) + } + + then: + "norman".capitalize() == "Norman" + String.joinWith(" -> ", "a", "b", "c") == "a -> b -> c" } - void testEmployeeExtension() { + def "testEmployeeExtension"() { + given: def age = 28 def expectedYearOfBirth = Year.now() - age Employee emp = new Employee(age: age) - assert emp.getYearOfBirth() == expectedYearOfBirth.value + + expect: + emp.getYearOfBirth() == expectedYearOfBirth.value } - void testJavaClassesExtensions() { + def "testJavaClassesExtensions"() { + when: 5.printCounter() - assert 40l.square() == 1600l - - assert (2.98).cube() == 26.463592 + then: + 40L.square() == 1600L + (2.98).cube() == 26.463592 } - void testStaticEmployeeExtension() { + def "testStaticEmployeeExtension"() { assert Employee.getDefaultObj().firstName == "firstName" assert Employee.getDefaultObj().lastName == "lastName" assert Employee.getDefaultObj().age == 20 } - void testToStringAnnotation() { - Employee employee = new Employee() - employee.id = 1 - employee.firstName = "norman" - employee.lastName = "lewis" - employee.age = 28 + def "testToStringAnnotation"() { + when: + Employee employee = new Employee().tap { + id = 1 + firstName = "norman" + lastName = "lewis" + age = 28 + } - assert employee.toString() == "Employee(norman, lewis, 28)" + then: + employee.toString() == "Employee(norman, lewis, 28)" } - void testTupleConstructorAnnotation() { + def "testTupleConstructorAnnotation"() { + when: Employee norman = new Employee(1, "norman", "lewis", 28) - assert norman.toString() == "Employee(norman, lewis, 28)" - Employee snape = new Employee(2, "snape") - assert snape.toString() == "Employee(snape, null, 0)" + then: + norman.toString() == "Employee(norman, lewis, 28)" + snape.toString() == "Employee(snape, null, 0)" } - - void testEqualsAndHashCodeAnnotation() { + + def "testEqualsAndHashCodeAnnotation"() { + when: Employee norman = new Employee(1, "norman", "lewis", 28) Employee normanCopy = new Employee(1, "norman", "lewis", 28) - assert norman.equals(normanCopy) - assert norman.hashCode() == normanCopy.hashCode() - } - - void testAutoCloneAnnotation() { - try { - Employee norman = new Employee(1, "norman", "lewis", 28) - def normanCopy = norman.clone() - assert norman == normanCopy - } catch(CloneNotSupportedException e) { - e.printStackTrace() - } + + then: + norman == normanCopy + norman.hashCode() == normanCopy.hashCode() } - void testLoggingAnnotation() { + def "testAutoCloneAnnotation"() { + given: + Employee norman = new Employee(1, "norman", "lewis", 28) + + when: + def normanCopy = norman.clone() + + then: + norman == normanCopy + } + + def "testLoggingAnnotation"() { + given: Employee employee = new Employee(1, "Norman", "Lewis", 28) - employee.logEmp() + employee.logEmp() // INFO: Employee: Lewis, Norman is of 28 years age } } From 46ac54b723afc17e1636dc4d3f7e2fc4b36cd7a6 Mon Sep 17 00:00:00 2001 From: Alex Golub Date: Fri, 20 Jan 2023 12:55:56 +0200 Subject: [PATCH 11/16] Categories: code reformat --- .../baeldung/category/BaeldungCategory.groovy | 16 +++++----- .../baeldung/category/NumberCategory.groovy | 14 ++++----- .../baeldung/category/CategoryUnitTest.groovy | 31 +++++++++---------- 3 files changed, 29 insertions(+), 32 deletions(-) diff --git a/core-groovy-modules/core-groovy-2/src/main/groovy/com/baeldung/category/BaeldungCategory.groovy b/core-groovy-modules/core-groovy-2/src/main/groovy/com/baeldung/category/BaeldungCategory.groovy index 479c39699f..ccb1c7fc95 100644 --- a/core-groovy-modules/core-groovy-2/src/main/groovy/com/baeldung/category/BaeldungCategory.groovy +++ b/core-groovy-modules/core-groovy-2/src/main/groovy/com/baeldung/category/BaeldungCategory.groovy @@ -1,17 +1,17 @@ -package com.baeldung.category; +package com.baeldung.category class BaeldungCategory { - public static String capitalize(String self) { - String capitalizedStr = self; + static String capitalize(String self) { + String capitalizedStr = self if (self.size() > 0) { - capitalizedStr = self.substring(0, 1).toUpperCase() + self.substring(1); + capitalizedStr = self.substring(0, 1).toUpperCase() + self.substring(1) } + return capitalizedStr } - - public static double toThePower(Number self, Number exponent) { - return Math.pow(self, exponent); - } + static double toThePower(Number self, Number exponent) { + return Math.pow(self, exponent) + } } diff --git a/core-groovy-modules/core-groovy-2/src/main/groovy/com/baeldung/category/NumberCategory.groovy b/core-groovy-modules/core-groovy-2/src/main/groovy/com/baeldung/category/NumberCategory.groovy index ccf2ed519b..4f38b87ec5 100644 --- a/core-groovy-modules/core-groovy-2/src/main/groovy/com/baeldung/category/NumberCategory.groovy +++ b/core-groovy-modules/core-groovy-2/src/main/groovy/com/baeldung/category/NumberCategory.groovy @@ -1,17 +1,15 @@ -package com.baeldung.category; - -import groovy.lang.Category +package com.baeldung.category @Category(Number) class NumberCategory { - public Number cube() { - return this*this*this + Number cube() { + return this**3 } - public int divideWithRoundUp(BigDecimal divisor, boolean isRoundUp) { + int divideWithRoundUp(BigDecimal divisor, boolean isRoundUp) { def mathRound = isRoundUp ? BigDecimal.ROUND_UP : BigDecimal.ROUND_DOWN - return (int)new BigDecimal(this).divide(divisor, 0, mathRound) + + return (int) new BigDecimal(this).divide(divisor, 0, mathRound) } - } diff --git a/core-groovy-modules/core-groovy-2/src/test/groovy/com/baeldung/category/CategoryUnitTest.groovy b/core-groovy-modules/core-groovy-2/src/test/groovy/com/baeldung/category/CategoryUnitTest.groovy index a1f67b1e2e..370dfb316e 100644 --- a/core-groovy-modules/core-groovy-2/src/test/groovy/com/baeldung/category/CategoryUnitTest.groovy +++ b/core-groovy-modules/core-groovy-2/src/test/groovy/com/baeldung/category/CategoryUnitTest.groovy @@ -1,17 +1,17 @@ package com.baeldung.category -import groovy.time.* +import groovy.time.TimeCategory +import groovy.xml.DOMBuilder +import groovy.xml.QName +import groovy.xml.dom.DOMCategory + import java.text.SimpleDateFormat -import groovy.xml.* -import groovy.xml.dom.* -import com.baeldung.category.BaeldungCategory -import com.baeldung.category.NumberCategory class CategoryUnitTest extends GroovyTestCase { void test_whenUsingTimeCategory_thenOperationOnDate() { def jan_1_2019 = new Date("01/01/2019") - use (TimeCategory) { + use(TimeCategory) { assert jan_1_2019 + 10.seconds == new Date("01/01/2019 00:00:10") assert jan_1_2019 + 20.minutes == new Date("01/01/2019 00:20:00") @@ -30,7 +30,7 @@ class CategoryUnitTest extends GroovyTestCase { void test_whenUsingTimeCategory_thenOperationOnNumber() { SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy") - use (TimeCategory) { + use(TimeCategory) { assert sdf.format(5.days.from.now) == sdf.format(new Date() + 5.days) sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss") @@ -57,7 +57,7 @@ class CategoryUnitTest extends GroovyTestCase { def root = baeldungArticlesDom.documentElement - use (DOMCategory) { + use(DOMCategory) { assert root.article.size() == 2 def articles = root.article @@ -75,27 +75,26 @@ class CategoryUnitTest extends GroovyTestCase { assert root.article[2].title.text() == "Metaprogramming in Groovy" } } - + void test_whenUsingBaeldungCategory_thenCapitalizeString() { - use (BaeldungCategory) { + use(BaeldungCategory) { assert "norman".capitalize() == "Norman" - } + } } - + void test_whenUsingBaeldungCategory_thenOperationsOnNumber() { - use (BaeldungCategory) { + use(BaeldungCategory) { assert 50.toThePower(2) == 2500 assert 2.4.toThePower(4) == 33.1776 } } - + void test_whenUsingNumberCategory_thenOperationsOnNumber() { - use (NumberCategory) { + use(NumberCategory) { assert 3.cube() == 27 assert 25.divideWithRoundUp(6, true) == 5 assert 120.23.divideWithRoundUp(6.1, true) == 20 assert 150.9.divideWithRoundUp(12.1, false) == 12 } } - } From 3512ca847faca394abeb688418b3271d9fcb5696 Mon Sep 17 00:00:00 2001 From: Alex Golub Date: Fri, 20 Jan 2023 15:01:35 +0200 Subject: [PATCH 12/16] Maps in Groovy: convert to spock test framework --- .../groovy/com/baeldung/maps/MapTest.groovy | 212 +++++++++--------- 1 file changed, 112 insertions(+), 100 deletions(-) diff --git a/core-groovy-modules/core-groovy-collections/src/test/groovy/com/baeldung/maps/MapTest.groovy b/core-groovy-modules/core-groovy-collections/src/test/groovy/com/baeldung/maps/MapTest.groovy index deb552c420..9529330089 100644 --- a/core-groovy-modules/core-groovy-collections/src/test/groovy/com/baeldung/maps/MapTest.groovy +++ b/core-groovy-modules/core-groovy-collections/src/test/groovy/com/baeldung/maps/MapTest.groovy @@ -1,148 +1,160 @@ -package com.baeldung.maps; +package com.baeldung.maps -import static groovy.test.GroovyAssert.* -import org.junit.Test +import spock.lang.Specification -class MapTest{ - - @Test - void createMap() { +class MapTest extends Specification { + def "createMap"() { + when: def emptyMap = [:] - assertNotNull(emptyMap) + def map = [name: "Jerry", age: 42, city: "New York"] - assertTrue(emptyMap instanceof java.util.LinkedHashMap) - - def map = [name:"Jerry", age: 42, city: "New York"] - assertTrue(map.size() == 3) + then: + emptyMap != null + emptyMap instanceof java.util.LinkedHashMap + map.size() == 3 } - @Test - void addItemsToMap() { - - def map = [name:"Jerry"] - - map["age"] = 42 - - map.city = "New York" - + def "addItemsToMap"() { + given: + def map = [name: "Jerry"] def hobbyLiteral = "hobby" def hobbyMap = [(hobbyLiteral): "Singing"] + def appendToMap = [:] + + when: + map["age"] = 42 + map.city = "New York" + map.putAll(hobbyMap) - assertTrue(map == [name:"Jerry", age: 42, city: "New York", hobby:"Singing"]) - assertTrue(hobbyMap.hobby == "Singing") - assertTrue(hobbyMap[hobbyLiteral] == "Singing") - - map.plus([1:20]) // returns new map + appendToMap.plus([1: 20]) + appendToMap << [2: 30] - map << [2:30] + then: + map == [name: "Jerry", age: 42, city: "New York", hobby: "Singing"] + hobbyMap.hobby == "Singing" + hobbyMap[hobbyLiteral] == "Singing" + + appendToMap == [2: 30] // plus(Map) returns new instance of Map } - @Test - void getItemsFromMap() { - - def map = [name:"Jerry", age: 42, city: "New York", hobby:"Singing"] - - assertTrue(map["name"] == "Jerry") - - assertTrue(map.name == "Jerry") - + def "getItemsFromMap"() { + when: + def map = [name: "Jerry", age: 42, city: "New York", hobby: "Singing"] def propertyAge = "age" - assertTrue(map[propertyAge] == 42) + + then: + map["name"] == "Jerry" + map.name == "Jerry" + map[propertyAge] == 42 + map."$propertyAge" == 42 } - @Test - void removeItemsFromMap() { + def "removeItemsFromMap"() { + given: + def map = [1: 20, a: 30, 2: 42, 4: 34, ba: 67, 6: 39, 7: 49] + def removeAllKeysOfTypeString = [1: 20, a: 30, ba: 67, 6: 39, 7: 49] + def retainAllEntriesWhereValueIsEven = [1: 20, a: 30, ba: 67, 6: 39, 7: 49] - def map = [1:20, a:30, 2:42, 4:34, ba:67, 6:39, 7:49] + when: + def minusMap = map - [2: 42, 4: 34] + removeAllKeysOfTypeString.removeAll { it.key instanceof String } + retainAllEntriesWhereValueIsEven.retainAll { it.value % 2 == 0 } - def minusMap = map.minus([2:42, 4:34]); - assertTrue(minusMap == [1:20, a:30, ba:67, 6:39, 7:49]) - - minusMap.removeAll{it -> it.key instanceof String} - assertTrue( minusMap == [ 1:20, 6:39, 7:49]) - - minusMap.retainAll{it -> it.value %2 == 0} - assertTrue( minusMap == [1:20]) + then: + minusMap == [1: 20, a: 30, ba: 67, 6: 39, 7: 49] + removeAllKeysOfTypeString == [1: 20, 6: 39, 7: 49] + retainAllEntriesWhereValueIsEven == [1: 20, a: 30] } - @Test - void iteratingOnMaps(){ - def map = [name:"Jerry", age: 42, city: "New York", hobby:"Singing"] + def "iteratingOnMaps"() { + when: + def map = [name: "Jerry", age: 42, city: "New York", hobby: "Singing"] - map.each{ entry -> println "$entry.key: $entry.value" } - - map.eachWithIndex{ entry, i -> println "$i $entry.key: $entry.value" } - - map.eachWithIndex{ key, value, i -> println "$i $key: $value" } + then: + map.each { entry -> println "$entry.key: $entry.value" } + map.eachWithIndex { entry, i -> println "$i $entry.key: $entry.value" } + map.eachWithIndex { key, value, i -> println "$i $key: $value" } } - @Test - void filteringAndSearchingMaps(){ - def map = [name:"Jerry", age: 42, city: "New York", hobby:"Singing"] + def "filteringAndSearchingMaps"() { + given: + def map = [name: "Jerry", age: 42, city: "New York", hobby: "Singing"] - assertTrue(map.find{ it.value == "New York"}.key == "city") + when: + def find = map.find { it.value == "New York" } + def finaAll = map.findAll { it.value == "New York" } + def grep = map.grep { it.value == "New York" } + def every = map.every { it -> it.value instanceof String } + def any = map.any { it -> it.value instanceof String } - assertTrue(map.findAll{ it.value == "New York"} == [city : "New York"]) + then: + find.key == "city" - map.grep{it.value == "New York"}.each{ it -> assertTrue(it.key == "city" && it.value == "New York")} + finaAll instanceof Map + finaAll == [city: "New York"] - assertTrue(map.every{it -> it.value instanceof String} == false) + grep instanceof Collection + grep.each { it -> assert it.key == "city" && it.value == "New York" } - assertTrue(map.any{it -> it.value instanceof String} == true) + every instanceof Boolean + !every + + any instanceof Boolean + any } - @Test - void collect(){ - - def map = [1: [name:"Jerry", age: 42, city: "New York"], - 2: [name:"Long", age: 25, city: "New York"], - 3: [name:"Dustin", age: 29, city: "New York"], - 4: [name:"Dustin", age: 34, city: "New York"]] - - def names = map.collect{entry -> entry.value.name} // returns only list - assertTrue(names == ["Jerry", "Long", "Dustin", "Dustin"]) - - def uniqueNames = map.collect([] as HashSet){entry -> entry.value.name} - assertTrue(uniqueNames == ["Jerry", "Long", "Dustin"] as Set) - - def idNames = map.collectEntries{key, value -> [key, value.name]} - assertTrue(idNames == [1:"Jerry", 2: "Long", 3:"Dustin", 4: "Dustin"]) - - def below30Names = map.findAll{it.value.age < 30}.collect{key, value -> value.name} - assertTrue(below30Names == ["Long", "Dustin"]) + def "collect"() { + given: + def map = [ + 1: [name: "Jerry", age: 42, city: "New York"], + 2: [name: "Long", age: 25, city: "New York"], + 3: [name: "Dustin", age: 29, city: "New York"], + 4: [name: "Dustin", age: 34, city: "New York"] + ] + when: + def names = map.collect { entry -> entry.value.name } // returns only list + def uniqueNames = map.collect { entry -> entry.value.name } + .unique() + def idNames = map.collectEntries { key, value -> [key, value.name] } + def below30Names = map.findAll { it.value.age < 30 } + .collect { key, value -> value.name } + then: + names == ["Jerry", "Long", "Dustin", "Dustin"] + uniqueNames == ["Jerry", "Long", "Dustin"] + idNames == [1: "Jerry", 2: "Long", 3: "Dustin", 4: "Dustin"] + below30Names == ["Long", "Dustin"] } - @Test - void group(){ - def map = [1:20, 2: 40, 3: 11, 4: 93] - - def subMap = map.groupBy{it.value % 2} - println subMap - assertTrue(subMap == [0:[1:20, 2:40 ], 1:[3:11, 4:93]]) + def "group"() { + given: + def map = [1: 20, 2: 40, 3: 11, 4: 93] + when: + def subMap = map.groupBy { it.value % 2 } def keySubMap = map.subMap([1, 2]) - assertTrue(keySubMap == [1:20, 2:40]) + then: + subMap == [0: [1: 20, 2: 40], 1: [3: 11, 4: 93]] + keySubMap == [1: 20, 2: 40] } - @Test - void sorting(){ - def map = [ab:20, a: 40, cb: 11, ba: 93] + def "sorting"() { + given: + def map = [ab: 20, a: 40, cb: 11, ba: 93] + when: def naturallyOrderedMap = map.sort() - assertTrue([a:40, ab:20, ba:93, cb:11] == naturallyOrderedMap) - def compSortedMap = map.sort({ k1, k2 -> k1 <=> k2 } as Comparator) - assertTrue([a:40, ab:20, ba:93, cb:11] == compSortedMap) - def cloSortedMap = map.sort({ it1, it2 -> it1.value <=> it1.value }) - assertTrue([cb:11, ab:20, a:40, ba:93] == cloSortedMap) + then: + naturallyOrderedMap == [a: 40, ab: 20, ba: 93, cb: 11] + compSortedMap == [a: 40, ab: 20, ba: 93, cb: 11] + cloSortedMap == [cb: 11, ab: 20, a: 40, ba: 93] } - } From 76fb5b02e0ef7a04fdf14940852522d0acfc0d76 Mon Sep 17 00:00:00 2001 From: Alex Golub Date: Fri, 20 Jan 2023 18:27:09 +0200 Subject: [PATCH 13/16] Finding Elements in Collections in Groovy: refactor to use spock testing framework --- .../com/baeldung/find/ListFindUnitTest.groovy | 71 ++++++------ .../com/baeldung/find/MapFindUnitTest.groovy | 105 +++++++++--------- .../groovy/com/baeldung/find/Person.groovy | 39 +------ .../com/baeldung/find/SetFindUnitTest.groovy | 17 ++- 4 files changed, 104 insertions(+), 128 deletions(-) diff --git a/core-groovy-modules/core-groovy-collections/src/test/groovy/com/baeldung/find/ListFindUnitTest.groovy b/core-groovy-modules/core-groovy-collections/src/test/groovy/com/baeldung/find/ListFindUnitTest.groovy index 82a2138be4..325cf18c5f 100644 --- a/core-groovy-modules/core-groovy-collections/src/test/groovy/com/baeldung/find/ListFindUnitTest.groovy +++ b/core-groovy-modules/core-groovy-collections/src/test/groovy/com/baeldung/find/ListFindUnitTest.groovy @@ -1,58 +1,57 @@ package com.baeldung.find -import com.baeldung.find.Person -import org.junit.Test +import spock.lang.Specification -import static org.junit.Assert.* +class ListFindUnitTest extends Specification { -class ListFindUnitTest { - - private final personList = [ - new Person("Regina", "Fitzpatrick", 25), - new Person("Abagail", "Ballard", 26), - new Person("Lucian", "Walter", 30), + final personList = [ + new Person("Regina", "Fitzpatrick", 25), + new Person("Abagail", "Ballard", 26), + new Person("Lucian", "Walter", 30), ] - @Test - void whenListContainsElement_thenCheckReturnsTrue() { + def "whenListContainsElement_thenCheckReturnsTrue"() { + given: def list = ['a', 'b', 'c'] - assertTrue(list.indexOf('a') > -1) - assertTrue(list.contains('a')) + expect: + list.indexOf('a') > -1 + list.contains('a') } - @Test - void whenListContainsElement_thenCheckWithMembershipOperatorReturnsTrue() { + def "whenListContainsElement_thenCheckWithMembershipOperatorReturnsTrue"() { + given: def list = ['a', 'b', 'c'] - assertTrue('a' in list) + expect: + 'a' in list } - @Test - void givenListOfPerson_whenUsingStreamMatching_thenShouldEvaluateList() { - assertTrue(personList.stream().anyMatch {it.age > 20}) - assertFalse(personList.stream().allMatch {it.age < 30}) + def "givenListOfPerson_whenUsingStreamMatching_thenShouldEvaluateList"() { + expect: + personList.stream().anyMatch { it.age > 20 } + !personList.stream().allMatch { it.age < 30 } } - @Test - void givenListOfPerson_whenUsingCollectionMatching_thenShouldEvaluateList() { - assertTrue(personList.any {it.age > 20}) - assertFalse(personList.every {it.age < 30}) + def "givenListOfPerson_whenUsingCollectionMatching_thenShouldEvaluateList"() { + expect: + personList.any { it.age > 20 } + !personList.every { it.age < 30 } } - @Test - void givenListOfPerson_whenUsingStreamFind_thenShouldReturnMatchingElements() { - assertTrue(personList.stream().filter {it.age > 20}.findAny().isPresent()) - assertFalse(personList.stream().filter {it.age > 30}.findAny().isPresent()) - assertTrue(personList.stream().filter {it.age > 20}.findAll().size() == 3) - assertTrue(personList.stream().filter {it.age > 30}.findAll().isEmpty()) + def "givenListOfPerson_whenUsingStreamFind_thenShouldReturnMatchingElements"() { + expect: + personList.stream().filter { it.age > 20 }.findAny().isPresent() + !personList.stream().filter { it.age > 30 }.findAny().isPresent() + personList.stream().filter { it.age > 20 }.findAll().size() == 3 + personList.stream().filter { it.age > 30 }.findAll().isEmpty() } - @Test - void givenListOfPerson_whenUsingCollectionFind_thenShouldReturnMatchingElements() { - assertNotNull(personList.find {it.age > 20}) - assertNull(personList.find {it.age > 30}) - assertTrue(personList.findAll {it.age > 20}.size() == 3) - assertTrue(personList.findAll {it.age > 30}.isEmpty()) + def "givenListOfPerson_whenUsingCollectionFind_thenShouldReturnMatchingElements"() { + expect: + personList.find { it.age > 20 } == new Person("Regina", "Fitzpatrick", 25) + personList.find { it.age > 30 } == null + personList.findAll { it.age > 20 }.size() == 3 + personList.findAll { it.age > 30 }.isEmpty() } } diff --git a/core-groovy-modules/core-groovy-collections/src/test/groovy/com/baeldung/find/MapFindUnitTest.groovy b/core-groovy-modules/core-groovy-collections/src/test/groovy/com/baeldung/find/MapFindUnitTest.groovy index 16e231182b..74d85ad71b 100644 --- a/core-groovy-modules/core-groovy-collections/src/test/groovy/com/baeldung/find/MapFindUnitTest.groovy +++ b/core-groovy-modules/core-groovy-collections/src/test/groovy/com/baeldung/find/MapFindUnitTest.groovy @@ -1,76 +1,81 @@ package com.baeldung.find -import com.baeldung.find.Person -import org.junit.Test +import spock.lang.Specification -import static org.junit.Assert.* +class MapFindUnitTest extends Specification { -class MapFindUnitTest { - - private final personMap = [ - Regina : new Person("Regina", "Fitzpatrick", 25), - Abagail: new Person("Abagail", "Ballard", 26), - Lucian : new Person("Lucian", "Walter", 30) + final personMap = [ + Regina: new Person("Regina", "Fitzpatrick", 25), + Abagail: new Person("Abagail", "Ballard", 26), + Lucian: new Person("Lucian", "Walter", 30) ] - @Test - void whenMapContainsKeyElement_thenCheckReturnsTrue() { + def "whenMapContainsKeyElement_thenCheckReturnsTrue"() { + given: def map = [a: 'd', b: 'e', c: 'f'] - assertTrue(map.containsKey('a')) - assertFalse(map.containsKey('e')) - assertTrue(map.containsValue('e')) + expect: + map.containsKey('a') + !map.containsKey('e') + map.containsValue('e') } - @Test - void whenMapContainsKeyElement_thenCheckByMembershipReturnsTrue() { + def "whenMapContainsKeyElement_thenCheckByMembershipReturnsTrue"() { + given: def map = [a: 'd', b: 'e', c: 'f'] - assertTrue('a' in map) - assertFalse('f' in map) + expect: + 'a' in map + 'f' !in map } - @Test - void whenMapContainsFalseBooleanValues_thenCheckReturnsFalse() { + def "whenMapContainsFalseBooleanValues_thenCheckReturnsFalse"() { + given: def map = [a: true, b: false, c: null] - assertTrue(map.containsKey('b')) - assertTrue('a' in map) - assertFalse('b' in map) - assertFalse('c' in map) + expect: + map.containsKey('b') + 'a' in map + 'b' !in map // get value of key 'b' and does the assertion + 'c' !in map } - @Test - void givenMapOfPerson_whenUsingStreamMatching_thenShouldEvaluateMap() { - assertTrue(personMap.keySet().stream().anyMatch {it == "Regina"}) - assertFalse(personMap.keySet().stream().allMatch {it == "Albert"}) - assertFalse(personMap.values().stream().allMatch {it.age < 30}) - assertTrue(personMap.entrySet().stream().anyMatch {it.key == "Abagail" && it.value.lastname == "Ballard"}) + def "givenMapOfPerson_whenUsingStreamMatching_thenShouldEvaluateMap"() { + expect: + personMap.keySet().stream() + .anyMatch { it == "Regina" } + !personMap.keySet().stream() + .allMatch { it == "Albert" } + !personMap.values().stream() + .allMatch { it.age < 30 } + personMap.entrySet().stream() + .anyMatch { it.key == "Abagail" && it.value.lastname == "Ballard" } } - @Test - void givenMapOfPerson_whenUsingCollectionMatching_thenShouldEvaluateMap() { - assertTrue(personMap.keySet().any {it == "Regina"}) - assertFalse(personMap.keySet().every {it == "Albert"}) - assertFalse(personMap.values().every {it.age < 30}) - assertTrue(personMap.any {firstname, person -> firstname == "Abagail" && person.lastname == "Ballard"}) + def "givenMapOfPerson_whenUsingCollectionMatching_thenShouldEvaluateMap"() { + expect: + personMap.keySet().any { it == "Regina" } + !personMap.keySet().every { it == "Albert" } + !personMap.values().every { it.age < 30 } + personMap.any { firstname, person -> firstname == "Abagail" && person.lastname == "Ballard" } } - @Test - void givenMapOfPerson_whenUsingCollectionFind_thenShouldReturnElements() { - assertNotNull(personMap.find {it.key == "Abagail" && it.value.lastname == "Ballard"}) - assertTrue(personMap.findAll {it.value.age > 20}.size() == 3) + def "givenMapOfPerson_whenUsingCollectionFind_thenShouldReturnElements"() { + expect: + personMap.find { it.key == "Abagail" && it.value.lastname == "Ballard" } + personMap.findAll { it.value.age > 20 }.size() == 3 } - @Test - void givenMapOfPerson_whenUsingStreamFind_thenShouldReturnElements() { - assertTrue( - personMap.entrySet().stream() - .filter {it.key == "Abagail" && it.value.lastname == "Ballard"} - .findAny().isPresent()) - assertTrue( - personMap.entrySet().stream() - .filter {it.value.age > 20} - .findAll().size() == 3) + def "givenMapOfPerson_whenUsingStreamFind_thenShouldReturnElements"() { + expect: + personMap.entrySet().stream() + .filter { it.key == "Abagail" && it.value.lastname == "Ballard" } + .findAny() + .isPresent() + + personMap.entrySet().stream() + .filter { it.value.age > 20 } + .findAll() + .size() == 3 } } diff --git a/core-groovy-modules/core-groovy-collections/src/test/groovy/com/baeldung/find/Person.groovy b/core-groovy-modules/core-groovy-collections/src/test/groovy/com/baeldung/find/Person.groovy index e65826363a..a9266c4079 100644 --- a/core-groovy-modules/core-groovy-collections/src/test/groovy/com/baeldung/find/Person.groovy +++ b/core-groovy-modules/core-groovy-collections/src/test/groovy/com/baeldung/find/Person.groovy @@ -1,37 +1,10 @@ package com.baeldung.find +import groovy.transform.Canonical + +@Canonical class Person { - private String firstname - private String lastname - private Integer age - - Person(String firstname, String lastname, Integer age) { - this.firstname = firstname - this.lastname = lastname - this.age = age - } - - String getFirstname() { - return firstname - } - - void setFirstname(String firstname) { - this.firstname = firstname - } - - String getLastname() { - return lastname - } - - void setLastname(String lastname) { - this.lastname = lastname - } - - Integer getAge() { - return age - } - - void setAge(Integer age) { - this.age = age - } + String firstname + String lastname + Integer age } diff --git a/core-groovy-modules/core-groovy-collections/src/test/groovy/com/baeldung/find/SetFindUnitTest.groovy b/core-groovy-modules/core-groovy-collections/src/test/groovy/com/baeldung/find/SetFindUnitTest.groovy index d2d03d5427..d82cf689d3 100644 --- a/core-groovy-modules/core-groovy-collections/src/test/groovy/com/baeldung/find/SetFindUnitTest.groovy +++ b/core-groovy-modules/core-groovy-collections/src/test/groovy/com/baeldung/find/SetFindUnitTest.groovy @@ -1,16 +1,15 @@ package com.baeldung.find -import org.junit.Test +import spock.lang.Specification -import static org.junit.Assert.assertTrue +class SetFindUnitTest extends Specification { -class SetFindUnitTest { - - @Test - void whenSetContainsElement_thenCheckReturnsTrue() { + def "whenSetContainsElement_thenCheckReturnsTrue"() { + given: def set = ['a', 'b', 'c'] as Set - assertTrue(set.contains('a')) - assertTrue('a' in set) + expect: + set.contains('a') + 'a' in set } -} \ No newline at end of file +} From 66feff149a0cdc43f8fc9637d51f629248d60655 Mon Sep 17 00:00:00 2001 From: Alex Golub Date: Fri, 20 Jan 2023 19:17:04 +0200 Subject: [PATCH 14/16] Lists in Groovy: refactor to use spock testing framework --- .../com/baeldung/lists/ListUnitTest.groovy | 222 +++++++++--------- 1 file changed, 110 insertions(+), 112 deletions(-) diff --git a/core-groovy-modules/core-groovy-collections/src/test/groovy/com/baeldung/lists/ListUnitTest.groovy b/core-groovy-modules/core-groovy-collections/src/test/groovy/com/baeldung/lists/ListUnitTest.groovy index e4c0a0c177..5baa19f360 100644 --- a/core-groovy-modules/core-groovy-collections/src/test/groovy/com/baeldung/lists/ListUnitTest.groovy +++ b/core-groovy-modules/core-groovy-collections/src/test/groovy/com/baeldung/lists/ListUnitTest.groovy @@ -1,173 +1,171 @@ package com.baeldung.lists -import static groovy.test.GroovyAssert.* -import org.junit.Test +import spock.lang.Specification -class ListUnitTest { - - @Test - void testCreateList() { +class ListUnitTest extends Specification { + def "testCreateList"() { + when: def list = [1, 2, 3] - assertNotNull(list) - def listMix = ['A', "b", 1, true] - assertTrue(listMix == ['A', "b", 1, true]) - def linkedList = [1, 2, 3] as LinkedList - assertTrue(linkedList instanceof LinkedList) - ArrayList arrList = [1, 2, 3] - assertTrue(arrList.class == ArrayList) - def copyList = new ArrayList(arrList) - assertTrue(copyList == arrList) - def cloneList = arrList.clone() - assertTrue(cloneList == arrList) + + then: + list + listMix == ['A', "b", 1, true] + linkedList instanceof LinkedList + arrList.class == ArrayList + copyList == arrList + cloneList == arrList } - @Test - void testCreateEmptyList() { - + def "testCreateEmptyList"() { + when: def emptyList = [] - assertTrue(emptyList.size() == 0) + + then: + emptyList.isEmpty() } - @Test - void testCompareTwoLists() { - + def "testCompareTwoLists"() { + when: def list1 = [5, 6.0, 'p'] def list2 = [5, 6.0, 'p'] - assertTrue(list1 == list2) + + then: + list1 == list2 } - @Test - void testGetItemsFromList(){ - + def "testGetItemsFromList"() { + when: def list = ["Hello", "World"] - assertTrue(list.get(1) == "World") - assertTrue(list[1] == "World") - assertTrue(list[-1] == "World") - assertTrue(list.getAt(1) == "World") - assertTrue(list.getAt(-2) == "Hello") + then: + list.get(1) == "World" + list[1] == "World" + list[-1] == "World" + list.getAt(1) == "World" + list.getAt(-2) == "Hello" } - @Test - void testAddItemsToList() { + def "testAddItemsToList"() { + given: + def list1 = [] + def list2 = [] + def list3 = [1, 2] - def list = [] + when: + list1 << 1 // [1] + list1.add("Apple") // [1, "Apple"] - list << 1 - list.add("Apple") - assertTrue(list == [1, "Apple"]) + list2[2] = "Box" // [null, "Box"] + list2[4] = true // [null, "Box", null, true] - list[2] = "Box" - list[4] = true - assertTrue(list == [1, "Apple", "Box", null, true]) + list1.add(1, 6.0) // [1, 6.0, "Apple"] + list1 += list3 // [1, 6.0, "Apple", 1, 2] + list1 += 12 // [1, 6.0, "Apple", 1, 2, 12] - list.add(1, 6.0) - assertTrue(list == [1, 6.0, "Apple", "Box", null, true]) - - def list2 = [1, 2] - list += list2 - list += 12 - assertTrue(list == [1, 6.0, "Apple", "Box", null, true, 1, 2, 12]) + then: + list1 == [1, 6.0, "Apple", 1, 2, 12] + list2 == [null, null, "Box", null, true] } - @Test - void testUpdateItemsInList() { + def "testUpdateItemsInList"() { + given: + def list = [1, "Apple", 80, "App"] - def list =[1, "Apple", 80, "App"] + when: list[1] = "Box" - list.set(2,90) - assertTrue(list == [1, "Box", 90, "App"]) + list.set(2, 90) + + then: + list == [1, "Box", 90, "App"] } - @Test - void testRemoveItemsFromList(){ - + def "testRemoveItemsFromList"() { + given: def list = [1, 2, 3, 4, 5, 5, 6, 6, 7] - list.remove(3) - assertTrue(list == [1, 2, 3, 5, 5, 6, 6, 7]) + when: + list.remove(3) // [1, 2, 3, 5, 5, 6, 6, 7] + list.removeElement(5) // [1, 2, 3, 5, 6, 6, 7] + list = list - 6 // [1, 2, 3, 5, 7] - list.removeElement(5) - assertTrue(list == [1, 2, 3, 5, 6, 6, 7]) - - assertTrue(list - 6 == [1, 2, 3, 5, 7]) + then: + list == [1, 2, 3, 5, 7] } - @Test - void testIteratingOnAList(){ - + def "testIteratingOnAList"() { + given: def list = [1, "App", 3, 4] - list.each{ println it * 2} - list.eachWithIndex{ it, i -> println "$i : $it" } + expect: + list.each { println it * 2 } + list.eachWithIndex { it, i -> println "$i : $it" } } - @Test - void testCollectingToAnotherList(){ - + def "testCollectingToAnotherList"() { + given: def list = ["Kay", "Henry", "Justin", "Tom"] - assertTrue(list.collect{"Hi " + it} == ["Hi Kay", "Hi Henry", "Hi Justin", "Hi Tom"]) + + when: + def collect = list.collect { "Hi " + it } + + then: + collect == ["Hi Kay", "Hi Henry", "Hi Justin", "Hi Tom"] } - @Test - void testJoinItemsInAList(){ - assertTrue(["One", "Two", "Three"].join(",") == "One,Two,Three") + def "testJoinItemsInAList"() { + expect: + ["One", "Two", "Three"].join(",") == "One,Two,Three" } - @Test - void testFilteringOnLists(){ + def "testFilteringOnLists"() { + given: def filterList = [2, 1, 3, 4, 5, 6, 76] - - assertTrue(filterList.find{it > 3} == 4) - - assertTrue(filterList.findAll{it > 3} == [4, 5, 6, 76]) - - assertTrue(filterList.findAll{ it instanceof Number} == [2, 1, 3, 4, 5, 6, 76]) - - assertTrue(filterList.grep( Number )== [2, 1, 3, 4, 5, 6, 76]) - - assertTrue(filterList.grep{ it> 6 }== [76]) - def conditionList = [2, 1, 3, 4, 5, 6, 76] - assertFalse(conditionList.every{ it < 6}) - - assertTrue(conditionList.any{ it%2 == 0}) + expect: + filterList.find { it > 3 } == 4 + filterList.findAll { it > 3 } == [4, 5, 6, 76] + filterList.findAll { it instanceof Number } == [2, 1, 3, 4, 5, 6, 76] + filterList.grep(Number) == [2, 1, 3, 4, 5, 6, 76] + filterList.grep { it > 6 } == [76] + !(conditionList.every { it < 6 }) + conditionList.any { it % 2 == 0 } } - @Test - void testGetUniqueItemsInAList(){ - assertTrue([1, 3, 3, 4].toUnique() == [1, 3, 4]) - + def "testGetUniqueItemsInAList"() { + given: def uniqueList = [1, 3, 3, 4] - uniqueList.unique() - assertTrue(uniqueList == [1, 3, 4]) - assertTrue(["A", "B", "Ba", "Bat", "Cat"].toUnique{ it.size()} == ["A", "Ba", "Bat"]) + when: + uniqueList.unique(true) + + then: + [1, 3, 3, 4].toUnique() == [1, 3, 4] + uniqueList == [1, 3, 4] + ["A", "B", "Ba", "Bat", "Cat"].toUnique { it.size() } == ["A", "Ba", "Bat"] } - @Test - void testSorting(){ - - assertTrue([1, 2, 1, 0].sort() == [0, 1, 1, 2]) - Comparator mc = {a,b -> a == b? 0: a < b? 1 : -1} - + def "testSorting"() { + given: + Comparator naturalOrder = { a, b -> a == b ? 0 : a < b ? -1 : 1 } def list = [1, 2, 1, 0] - list.sort(mc) - assertTrue(list == [2, 1, 1, 0]) - def strList = ["na", "ppp", "as"] - assertTrue(strList.max() == "ppp") - - Comparator minc = {a,b -> a == b? 0: a < b? -1 : 1} def numberList = [3, 2, 0, 7] - assertTrue(numberList.min(minc) == 0) + + when: + list.sort(naturalOrder.reversed()) + + then: + list == [2, 1, 1, 0] + strList.max() == "ppp" + [1, 2, 1, 0].sort() == [0, 1, 1, 2] + numberList.min(naturalOrder) == 0 } -} \ No newline at end of file +} From f6fa7f8909e5ad1089463d905cbc4928b585371e Mon Sep 17 00:00:00 2001 From: Alex Golub Date: Fri, 20 Jan 2023 19:25:34 +0200 Subject: [PATCH 15/16] A Quick Guide to Iterating a Map in Groovy: refactor to use spock testing framework --- .../iteratemap/IterateMapUnitTest.groovy | 81 ++++++------------- 1 file changed, 25 insertions(+), 56 deletions(-) diff --git a/core-groovy-modules/core-groovy-collections/src/test/groovy/com/baeldung/iteratemap/IterateMapUnitTest.groovy b/core-groovy-modules/core-groovy-collections/src/test/groovy/com/baeldung/iteratemap/IterateMapUnitTest.groovy index 970203ce85..4cbcaee2d8 100644 --- a/core-groovy-modules/core-groovy-collections/src/test/groovy/com/baeldung/iteratemap/IterateMapUnitTest.groovy +++ b/core-groovy-modules/core-groovy-collections/src/test/groovy/com/baeldung/iteratemap/IterateMapUnitTest.groovy @@ -1,85 +1,54 @@ package com.baeldung.iteratemap -import com.baeldung.find.Person -import org.junit.Test +import spock.lang.Specification -import static org.junit.Assert.* +class IterateMapUnitTest extends Specification { -class IterateMapUnitTest { - - @Test - void whenUsingEach_thenMapIsIterated() { - def map = [ - 'FF0000' : 'Red', - '00FF00' : 'Lime', - '0000FF' : 'Blue', - 'FFFF00' : 'Yellow' - ] + final Map map = [ + 'FF0000': 'Red', + '00FF00': 'Lime', + '0000FF': 'Blue', + 'FFFF00': 'Yellow', + 'E6E6FA': 'Lavender', + 'D8BFD8': 'Thistle', + 'DDA0DD': 'Plum', + ] + def "whenUsingEach_thenMapIsIterated"() { + expect: map.each { println "Hex Code: $it.key = Color Name: $it.value" } } - @Test - void whenUsingEachWithEntry_thenMapIsIterated() { - def map = [ - 'E6E6FA' : 'Lavender', - 'D8BFD8' : 'Thistle', - 'DDA0DD' : 'Plum', - ] - + def "whenUsingEachWithEntry_thenMapIsIterated"() { + expect: map.each { entry -> println "Hex Code: $entry.key = Color Name: $entry.value" } } - @Test - void whenUsingEachWithKeyAndValue_thenMapIsIterated() { - def map = [ - '000000' : 'Black', - 'FFFFFF' : 'White', - '808080' : 'Gray' - ] - + def "whenUsingEachWithKeyAndValue_thenMapIsIterated"() { + expect: map.each { key, val -> println "Hex Code: $key = Color Name $val" } } - @Test - void whenUsingEachWithIndexAndEntry_thenMapIsIterated() { - def map = [ - '800080' : 'Purple', - '4B0082' : 'Indigo', - '6A5ACD' : 'Slate Blue' - ] - + def "whenUsingEachWithIndexAndEntry_thenMapIsIterated"() { + expect: map.eachWithIndex { entry, index -> - def indent = ((index == 0 || index % 2 == 0) ? " " : "") + def indent = index % 2 == 0 ? " " : "" println "$indent Hex Code: $entry.key = Color Name: $entry.value" } } - @Test - void whenUsingEachWithIndexAndKeyAndValue_thenMapIsIterated() { - def map = [ - 'FFA07A' : 'Light Salmon', - 'FF7F50' : 'Coral', - 'FF6347' : 'Tomato', - 'FF4500' : 'Orange Red' - ] - + def "whenUsingEachWithIndexAndKeyAndValue_thenMapIsIterated"() { + expect: map.eachWithIndex { key, val, index -> - def indent = ((index == 0 || index % 2 == 0) ? " " : "") + def indent = index % 2 == 0 ? " " : "" println "$indent Hex Code: $key = Color Name: $val" } } - @Test - void whenUsingForLoop_thenMapIsIterated() { - def map = [ - '2E8B57' : 'Seagreen', - '228B22' : 'Forest Green', - '008000' : 'Green' - ] - + def "whenUsingForLoop_thenMapIsIterated"() { + expect: for (entry in map) { println "Hex Code: $entry.key = Color Name: $entry.value" } From 41d8fffcc715fbea16c2601e9d571471849b6b2a Mon Sep 17 00:00:00 2001 From: Alex Golub Date: Fri, 20 Jan 2023 20:04:48 +0200 Subject: [PATCH 16/16] How to Remove a Prefix From Strings in Groovy: refactor to use spock testing framework --- .../removeprefix/RemovePrefixTest.groovy | 72 ++++++++++--------- 1 file changed, 38 insertions(+), 34 deletions(-) diff --git a/core-groovy-modules/core-groovy-strings/src/test/groovy/com/baeldung/removeprefix/RemovePrefixTest.groovy b/core-groovy-modules/core-groovy-strings/src/test/groovy/com/baeldung/removeprefix/RemovePrefixTest.groovy index 61b81fe1b2..8b7ce9c355 100644 --- a/core-groovy-modules/core-groovy-strings/src/test/groovy/com/baeldung/removeprefix/RemovePrefixTest.groovy +++ b/core-groovy-modules/core-groovy-strings/src/test/groovy/com/baeldung/removeprefix/RemovePrefixTest.groovy @@ -1,70 +1,74 @@ package com.baeldung.removeprefix -import org.junit.Assert -import org.junit.Test +import spock.lang.Specification -class RemovePrefixTest { +class RemovePrefixTest extends Specification { - - @Test - public void whenCasePrefixIsRemoved_thenReturnTrue() { + def "whenCasePrefixIsRemoved_thenReturnTrue"() { + given: def trimPrefix = { it.startsWith('Groovy-') ? it.minus('Groovy-') : it } - + + when: def actual = trimPrefix("Groovy-Tutorials at Baeldung") def expected = "Tutorials at Baeldung" - Assert.assertEquals(expected, actual) + then: + expected == actual } - @Test - public void whenPrefixIsRemoved_thenReturnTrue() { - + def "whenPrefixIsRemoved_thenReturnTrue"() { + given: String prefix = "groovy-" String trimPrefix = "Groovy-Tutorials at Baeldung" - def actual; - if(trimPrefix.startsWithIgnoreCase(prefix)) { + + when: + def actual + if (trimPrefix.startsWithIgnoreCase(prefix)) { actual = trimPrefix.substring(prefix.length()) } - def expected = "Tutorials at Baeldung" - Assert.assertEquals(expected, actual) + then: + expected == actual } - @Test - public void whenPrefixIsRemovedUsingRegex_thenReturnTrue() { - + def "whenPrefixIsRemovedUsingRegex_thenReturnTrue"() { + given: def regex = ~"^([Gg])roovy-" String trimPrefix = "Groovy-Tutorials at Baeldung" + + when: String actual = trimPrefix - regex - def expected = "Tutorials at Baeldung" - Assert.assertEquals(expected, actual) + then: + expected == actual } - @Test - public void whenPrefixIsRemovedUsingReplaceFirst_thenReturnTrue() { - def regex = ~"^groovy" - String trimPrefix = "groovyTutorials at Baeldung's groovy page" + def "whenPrefixIsRemovedUsingReplaceFirst_thenReturnTrue"() { + given: + def regex = ~"^groovy" + String trimPrefix = "groovyTutorials at Baeldung's groovy page" + + when: String actual = trimPrefix.replaceFirst(regex, "") - def expected = "Tutorials at Baeldung's groovy page" - - Assert.assertEquals(expected, actual) + + then: + expected == actual } - @Test - public void whenPrefixIsRemovedUsingReplaceAll_thenReturnTrue() { - + def "whenPrefixIsRemovedUsingReplaceAll_thenReturnTrue"() { + given: String trimPrefix = "groovyTutorials at Baeldung groovy" + + when: String actual = trimPrefix.replaceAll(/^groovy/, "") - def expected = "Tutorials at Baeldung groovy" - Assert.assertEquals(expected, actual) + then: + expected == actual } - -} \ No newline at end of file +}