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
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 = '''<xs xmlns:gsp='groovy-server-pages'>
<gsp:scriptlet>def emailContent = "Thanks for subscribing our services."</gsp:scriptlet>
<email>
@ -51,11 +65,16 @@ Baeldung"""
<signature>${signature}</signature>
</email>
</xs>'''
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()
}
}
}

View File

@ -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)
}
}
}

View File

@ -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"
}
}

View File

@ -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()
}

View File

@ -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
}
}

View File

@ -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
}
}

View File

@ -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()
}
}

View File

@ -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!'
}
}

View File

@ -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"
}
}