Align tests with `Spock` testing framework

This commit is contained in:
Alex Golub 2023-01-14 21:31:29 +02:00
parent c34a4ac328
commit 3d36abe4f8
9 changed files with 288 additions and 249 deletions

View File

@ -1,48 +1,62 @@
package com.baeldung.templateengine package com.baeldung.templateengine
import groovy.text.GStringTemplateEngine
import groovy.text.SimpleTemplateEngine import groovy.text.SimpleTemplateEngine
import groovy.text.StreamingTemplateEngine import groovy.text.StreamingTemplateEngine
import groovy.text.GStringTemplateEngine
import groovy.text.XmlTemplateEngine
import groovy.text.XmlTemplateEngine import groovy.text.XmlTemplateEngine
import groovy.text.markup.MarkupTemplateEngine import groovy.text.markup.MarkupTemplateEngine
import groovy.text.markup.TemplateConfiguration import groovy.text.markup.TemplateConfiguration
import spock.lang.Specification
class TemplateEnginesUnitTest extends GroovyTestCase { class TemplateEnginesUnitTest extends Specification {
def bindMap = [user: "Norman", signature: "Baeldung"] final Map BIND_MAP = [user: "Norman", signature: "Baeldung"]
void testSimpleTemplateEngine() { def "testSimpleTemplateEngine"() {
given:
def smsTemplate = 'Dear <% print user %>, Thanks for reading our Article. ${signature}' 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') def articleEmailTemplate = new File('src/main/resources/articleEmail.template')
bindMap.articleText = """1. Overview //can be a string larger than 64k
This is a tutorial article on Template Engines""" //can be a string larger than 64k BIND_MAP.articleText = """|1. Overview
|This is a tutorial article on Template Engines""".stripMargin()
def articleEmailText = new StreamingTemplateEngine().createTemplate(articleEmailTemplate).make(bindMap) when:
def articleEmailText = new StreamingTemplateEngine().createTemplate(articleEmailTemplate).make(BIND_MAP)
assert articleEmailText.toString() == """Dear Norman,
Please read the requested article below.
1. Overview
This is a tutorial article on Template Engines
From,
Baeldung"""
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 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 = '''<xs xmlns:gsp='groovy-server-pages'> def emailXmlTemplate = '''<xs xmlns:gsp='groovy-server-pages'>
<gsp:scriptlet>def emailContent = "Thanks for subscribing our services."</gsp:scriptlet> <gsp:scriptlet>def emailContent = "Thanks for subscribing our services."</gsp:scriptlet>
<email> <email>
@ -51,11 +65,16 @@ Baeldung"""
<signature>${signature}</signature> <signature>${signature}</signature>
</email> </email>
</xs>''' </xs>'''
def emailXml = new XmlTemplateEngine().createTemplate(emailXmlTemplate).make(bindMap)
when:
def emailXml = new XmlTemplateEngine().createTemplate(emailXmlTemplate).make(BIND_MAP)
then:
println emailXml.toString() println emailXml.toString()
} }
void testMarkupTemplateEngineHtml() { def "testMarkupTemplateEngineHtml"() {
given:
def emailHtmlTemplate = """html { def emailHtmlTemplate = """html {
head { head {
title('Service Subscription Email') title('Service Subscription Email')
@ -67,13 +86,15 @@ Baeldung"""
} }
}""" }"""
when:
def emailHtml = new MarkupTemplateEngine().createTemplate(emailHtmlTemplate).make() def emailHtml = new MarkupTemplateEngine().createTemplate(emailHtmlTemplate).make()
println emailHtml.toString()
then:
println emailHtml.toString()
} }
void testMarkupTemplateEngineXml() { def "testMarkupTemplateEngineXml"() {
given:
def emailXmlTemplate = """xmlDeclaration() def emailXmlTemplate = """xmlDeclaration()
xs{ xs{
email { email {
@ -83,14 +104,18 @@ Baeldung"""
} }
} }
""" """
TemplateConfiguration config = new TemplateConfiguration() TemplateConfiguration config = new TemplateConfiguration().with {
config.autoIndent = true autoIndent = true
config.autoEscape = true autoEscape = true
config.autoNewLine = true autoNewLine = true
def emailXml = new MarkupTemplateEngine(config).createTemplate(emailXmlTemplate).make() return it
println emailXml.toString()
} }
when:
def emailXml = new MarkupTemplateEngine(config).createTemplate(emailXmlTemplate).make()
then:
println emailXml.toString()
}
} }

View File

@ -1,6 +1,7 @@
package com.baeldung.strings; package com.baeldung.strings;
class Concatenate { class Concatenate {
String first = 'Hello' String first = 'Hello'
String last = 'Groovy' String last = 'Groovy'
@ -29,15 +30,22 @@ class Concatenate {
} }
String doConcatUsingArrayInjectMethod() { String doConcatUsingArrayInjectMethod() {
return [first,' ', last] return [first, ' ', last]
.inject(new StringBuffer('My name is '), { initial, name -> initial.append(name); return initial }).toString() .inject(new StringBuffer('My name is '), { initial, name -> initial.append(name) })
.toString()
} }
String doConcatUsingStringBuilder() { 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() { 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)
} }
} }

View File

@ -1,101 +1,88 @@
import com.baeldung.strings.Concatenate; import com.baeldung.strings.Concatenate
import spock.lang.Specification
class ConcatenateTest extends GroovyTestCase { class ConcatenateTest extends Specification {
void testSimpleConcat() { final Concatenate NAME = new Concatenate(first: 'Joe', last: 'Smith')
def name = new Concatenate() final String EXPECTED = "My name is Joe Smith";
name.first = 'Joe';
name.last = 'Smith'; def "SimpleConcat"() {
def expected = 'My name is Joe Smith' expect:
assertToString(name.doSimpleConcat(), expected) NAME.doSimpleConcat() == EXPECTED
} }
void testConcatUsingGString() { def "ConcatUsingGString"() {
def name = new Concatenate() expect:
name.first = "Joe"; NAME.doConcatUsingGString() == EXPECTED
name.last = "Smith";
def expected = "My name is Joe Smith"
assertToString(name.doConcatUsingGString(), expected)
} }
void testConcatUsingGStringClosures() { def "ConcatUsingGStringClosures"() {
def name = new Concatenate() expect:
name.first = "Joe"; NAME.doConcatUsingGStringClosures() == EXPECTED
name.last = "Smith";
def expected = "My name is Joe Smith"
assertToString(name.doConcatUsingGStringClosures(), expected)
} }
void testConcatUsingStringConcatMethod() { def "ConcatUsingStringConcatMethod"() {
def name = new Concatenate() expect:
name.first = "Joe"; NAME.doConcatUsingStringConcatMethod() == EXPECTED
name.last = "Smith";
def expected = "My name is Joe Smith"
assertToString(name.doConcatUsingStringConcatMethod(), expected)
} }
void testConcatUsingLeftShiftOperator() { def "ConcatUsingLeftShiftOperator"() {
def name = new Concatenate() expect:
name.first = "Joe"; NAME.doConcatUsingLeftShiftOperator() == EXPECTED
name.last = "Smith";
def expected = "My name is Joe Smith"
assertToString(name.doConcatUsingLeftShiftOperator(), expected)
} }
void testConcatUsingArrayJoinMethod() { def "ConcatUsingArrayJoinMethod"() {
def name = new Concatenate() expect:
name.first = "Joe"; NAME.doConcatUsingArrayJoinMethod() == EXPECTED
name.last = "Smith";
def expected = "My name is Joe Smith"
assertToString(name.doConcatUsingArrayJoinMethod(), expected)
} }
void testConcatUsingArrayInjectMethod() { def "ConcatUsingArrayInjectMethod"() {
def name = new Concatenate() expect:
name.first = "Joe"; NAME.doConcatUsingArrayInjectMethod() == EXPECTED
name.last = "Smith";
def expected = "My name is Joe Smith"
assertToString(name.doConcatUsingArrayInjectMethod(), expected)
} }
void testConcatUsingStringBuilder() { def "ConcatUsingStringBuilder"() {
def name = new Concatenate() expect:
name.first = "Joe"; NAME.doConcatUsingStringBuilder() == EXPECTED
name.last = "Smith";
def expected = "My name is Joe Smith"
assertToString(name.doConcatUsingStringBuilder(), expected)
} }
void testConcatUsingStringBuffer() { def "ConcatUsingStringBuffer"() {
def name = new Concatenate() expect:
name.first = "Joe"; NAME.doConcatUsingStringBuffer() == EXPECTED
name.last = "Smith";
def expected = "My name is Joe Smith"
assertToString(name.doConcatUsingStringBuffer(), expected)
} }
void testConcatMultilineUsingStringConcatMethod() { def "ConcatMultilineUsingStringConcatMethod"() {
def name = new Concatenate() when:
name.first = '''Joe NAME.first = '''Joe
Smith Smith
'''; '''
name.last = 'Junior'; NAME.last = 'Junior'
then:
def expected = '''My name is Joe def expected = '''My name is Joe
Smith Smith
Junior'''; Junior'''
assertToString(name.doConcatUsingStringConcatMethod(), expected) NAME.doConcatUsingStringConcatMethod() == expected
} }
void testGStringvsClosure(){ def "GStringvsClosure"() {
def first = "Joe"; given:
def last = "Smith"; def eagerGString = "My name is $NAME.first $NAME.last"
def eagerGString = "My name is $first $last" def lazyGString = "My name is ${-> NAME.first} ${-> NAME.last}"
def lazyGString = "My name is ${-> first} ${-> last}"
assert eagerGString == "My name is Joe Smith" expect:
assert lazyGString == "My name is Joe Smith" eagerGString == "My name is Joe Smith"
first = "David"; lazyGString == "My name is Joe Smith"
assert eagerGString == "My name is Joe Smith" }
assert lazyGString == "My name is David 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"
} }
} }

View File

@ -13,7 +13,7 @@ class StringMatchingSpec extends Specification {
expect: expect:
p instanceof Pattern 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*/ def digitPattern = ~/\d*/
digitPattern.matcher('4711').matches() digitPattern.matcher('4711').matches()
} }

View File

@ -1,110 +1,119 @@
package com.baeldung.stringtoint package com.baeldung.stringtoint
import org.junit.Test import spock.lang.Specification
import java.text.DecimalFormat import java.text.DecimalFormat
import static org.junit.Assert.assertEquals class ConvertStringToInt extends Specification {
import static org.junit.Assert.assertNull
class ConvertStringToInt { final String STRING_NUM = "123"
final int EXPECTED_INT = 123
@Test def "givenString_whenUsingAsInteger_thenConvertToInteger"() {
void givenString_whenUsingAsInteger_thenConvertToInteger() { given:
def stringNum = "123"
def invalidString = "123a" def invalidString = "123a"
Integer expectedInteger = 123 Integer integerNum = STRING_NUM as Integer
Integer integerNum = stringNum as Integer
when:
def intNum = invalidString?.isInteger() ? invalidString as Integer : null def intNum = invalidString?.isInteger() ? invalidString as Integer : null
assertNull(null, intNum) then:
assertEquals(integerNum, expectedInteger) intNum == null
integerNum == EXPECTED_INT
} }
@Test def "givenString_whenUsingAsInt_thenConvertToInt"() {
void givenString_whenUsingAsInt_thenConvertToInt() { given:
def stringNum = "123" int intNum = STRING_NUM as int
int expectedInt = 123
int intNum = stringNum as int
assertEquals(intNum, expectedInt) expect:
intNum == EXPECTED_INT
} }
@Test def "givenString_whenUsingToInteger_thenConvertToInteger"() {
void givenString_whenUsingToInteger_thenConvertToInteger() { given:
def stringNum = "123" int intNum = STRING_NUM.toInteger()
int expectedInt = 123
int intNum = stringNum.toInteger()
assertEquals(intNum, expectedInt) expect:
intNum == EXPECTED_INT
} }
@Test def "givenString_whenUsingParseInt_thenConvertToInteger"() {
void givenString_whenUsingParseInt_thenConvertToInteger() { given:
def stringNum = "123" int intNum = Integer.parseInt(STRING_NUM)
int expectedInt = 123
int intNum = Integer.parseInt(stringNum)
assertEquals(intNum, expectedInt) expect:
intNum == EXPECTED_INT
} }
@Test def "givenString_whenUsingValueOf_thenConvertToInteger"() {
void givenString_whenUsingValueOf_thenConvertToInteger() { given:
def stringNum = "123" int intNum = Integer.valueOf(STRING_NUM)
int expectedInt = 123
int intNum = Integer.valueOf(stringNum)
assertEquals(intNum, expectedInt) expect:
intNum == EXPECTED_INT
} }
@Test def "givenString_whenUsingIntValue_thenConvertToInteger"() {
void givenString_whenUsingIntValue_thenConvertToInteger() { given:
def stringNum = "123" int intNum = Integer.valueOf(STRING_NUM).intValue()
int expectedInt = 123
int intNum = new Integer(stringNum).intValue()
assertEquals(intNum, expectedInt) expect:
intNum == EXPECTED_INT
} }
@Test def "givenString_whenUsingNewInteger_thenConvertToInteger"() {
void givenString_whenUsingNewInteger_thenConvertToInteger() { given:
def stringNum = "123" Integer intNum = Integer.valueOf(STRING_NUM)
int expectedInt = 123
int intNum = new Integer(stringNum)
assertEquals(intNum, expectedInt) expect:
intNum == EXPECTED_INT
} }
@Test def "givenString_whenUsingDecimalFormat_thenConvertToInteger"() {
void givenString_whenUsingDecimalFormat_thenConvertToInteger() { given:
def stringNum = "123"
int expectedInt = 123
DecimalFormat decimalFormat = new DecimalFormat("#") 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) def "givenInvalidString_whenUsingAs_thenThrowNumberFormatException"() {
void givenInvalidString_whenUsingAs_thenThrowNumberFormatException() { given:
def invalidString = "123a" def invalidString = "123a"
when:
invalidString as Integer invalidString as Integer
then:
thrown(NumberFormatException)
} }
@Test(expected = NullPointerException.class) def "givenNullString_whenUsingToInteger_thenThrowNullPointerException"() {
void givenNullString_whenUsingToInteger_thenThrowNullPointerException() { given:
def invalidString = null def invalidString = null
when:
invalidString.toInteger() invalidString.toInteger()
then:
thrown(NullPointerException)
} }
@Test def "givenString_whenUsingIsInteger_thenCheckIfCorrectValue"() {
void givenString_whenUsingIsInteger_thenCheckIfCorrectValue() { given:
def invalidString = "123a" def invalidString = "123a"
def validString = "123" def validString = "123"
when:
def invalidNum = invalidString?.isInteger() ? invalidString as Integer : false def invalidNum = invalidString?.isInteger() ? invalidString as Integer : false
def correctNum = validString?.isInteger() ? validString as Integer : false def correctNum = validString?.isInteger() ? validString as Integer : false
assertEquals(false, invalidNum) then:
assertEquals(123, correctNum) !invalidNum
correctNum == 123
} }
} }

View File

@ -1,19 +1,18 @@
package groovy.com.baeldung.stringtypes package groovy.com.baeldung.stringtypes
import org.junit.Assert import spock.lang.Specification
import org.junit.Test
class CharacterInGroovy { class CharacterInGroovy extends Specification {
@Test def 'character'() {
void 'character'() { given:
char a = 'A' as char char a = 'A' as char
char b = 'B' as char char b = 'B' as char
char c = (char) 'C' char c = (char) 'C'
Assert.assertTrue(a instanceof Character) expect:
Assert.assertTrue(b instanceof Character) a instanceof Character
Assert.assertTrue(c instanceof Character) b instanceof Character
c instanceof Character
} }
} }

View File

@ -1,67 +1,76 @@
package groovy.com.baeldung.stringtypes package groovy.com.baeldung.stringtypes
import org.junit.Assert import spock.lang.Specification
import org.junit.Test
class DoubleQuotedString { class DoubleQuotedString extends Specification {
@Test def 'escape double quoted string'() {
void 'escape double quoted string'() { given:
def example = "Hello \"world\"!" def example = "Hello \"world\"!"
println(example) expect:
example == 'Hello "world"!'
} }
@Test def 'String ang GString'() {
void 'String ang GString'() { given:
def string = "example" def string = "example"
def stringWithExpression = "example${2}" def stringWithExpression = "example${2}"
Assert.assertTrue(string instanceof String) expect:
Assert.assertTrue(stringWithExpression instanceof GString) string instanceof String
Assert.assertTrue(stringWithExpression.toString() instanceof String) stringWithExpression instanceof GString
stringWithExpression.toString() instanceof String
} }
@Test def 'placeholder with variable'() {
void 'placeholder with variable'() { given:
def name = "John" def name = "John"
when:
def helloName = "Hello $name!".toString() def helloName = "Hello $name!".toString()
Assert.assertEquals("Hello John!", helloName) then:
helloName == "Hello John!"
} }
@Test def 'placeholder with expression'() {
void 'placeholder with expression'() { given:
def result = "result is ${2 * 2}".toString() def result = "result is ${2 * 2}".toString()
Assert.assertEquals("result is 4", result) expect:
result == "result is 4"
} }
@Test def 'placeholder with dotted access'() {
void 'placeholder with dotted access'() { given:
def person = [name: 'John'] def person = [name: 'John']
when:
def myNameIs = "I'm $person.name, and you?".toString() 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 def 'placeholder with method call'() {
void 'placeholder with method call'() { given:
def name = 'John' def name = 'John'
when:
def result = "Uppercase name: ${name.toUpperCase()}".toString() def result = "Uppercase name: ${name.toUpperCase()}".toString()
Assert.assertEquals("Uppercase name: JOHN", result) then:
result == "Uppercase name: JOHN"
} }
@Test def 'GString and String hashcode'() {
void 'GString and String hashcode'() { given:
def string = "2+2 is 4" def string = "2+2 is 4"
def gstring = "2+2 is ${4}" def gstring = "2+2 is ${4}"
Assert.assertTrue(string.hashCode() != gstring.hashCode()) expect:
string.hashCode() != gstring.hashCode()
} }
} }

View File

@ -1,15 +1,14 @@
package groovy.com.baeldung.stringtypes package groovy.com.baeldung.stringtypes
import org.junit.Assert import spock.lang.Specification
import org.junit.Test
class SingleQuotedString { class SingleQuotedString extends Specification {
@Test def 'single quoted string'() {
void 'single quoted string'() { given:
def example = 'Hello world' def example = 'Hello world!'
Assert.assertEquals('Hello world!', 'Hello' + ' world!') expect:
example == 'Hello' + ' world!'
} }
} }

View File

@ -1,26 +1,29 @@
package groovy.com.baeldung.stringtypes package groovy.com.baeldung.stringtypes
import org.junit.Assert import spock.lang.Specification
import org.junit.Test
class Strings { class Strings extends Specification {
@Test def 'string interpolation '() {
void 'string interpolation '() { given:
def name = "Kacper" def name = "Kacper"
when:
def result = "Hello ${name}!" def result = "Hello ${name}!"
Assert.assertEquals("Hello Kacper!", result.toString()) then:
result.toString() == "Hello Kacper!"
} }
@Test def 'string concatenation'() {
void 'string concatenation'() { given:
def first = "first" def first = "first"
def second = "second" def second = "second"
when:
def concatenation = first + second def concatenation = first + second
Assert.assertEquals("firstsecond", concatenation) then:
concatenation == "firstsecond"
} }
} }