|
| 1 | +package groovy.com.baeldung.stringtypes |
| 2 | + |
| 3 | +import org.junit.Assert |
| 4 | +import org.junit.Test |
| 5 | + |
| 6 | +class DoubleQuotedString { |
| 7 | + |
| 8 | + @Test |
| 9 | + void 'escape double quoted string'() { |
| 10 | + def example = "Hello \"world\"!" |
| 11 | + |
| 12 | + println(example) |
| 13 | + } |
| 14 | + |
| 15 | + @Test |
| 16 | + void 'String ang GString'() { |
| 17 | + def string = "example" |
| 18 | + def stringWithExpression = "example${2}" |
| 19 | + |
| 20 | + Assert.assertTrue(string instanceof String) |
| 21 | + Assert.assertTrue(stringWithExpression instanceof GString) |
| 22 | + Assert.assertTrue(stringWithExpression.toString() instanceof String) |
| 23 | + } |
| 24 | + |
| 25 | + @Test |
| 26 | + void 'placeholder with variable'() { |
| 27 | + def name = "John" |
| 28 | + def helloName = "Hello $name!".toString() |
| 29 | + |
| 30 | + Assert.assertEquals("Hello John!", helloName) |
| 31 | + } |
| 32 | + |
| 33 | + @Test |
| 34 | + void 'placeholder with expression'() { |
| 35 | + def result = "result is ${2 * 2}".toString() |
| 36 | + |
| 37 | + Assert.assertEquals("result is 4", result) |
| 38 | + } |
| 39 | + |
| 40 | + @Test |
| 41 | + void 'placeholder with dotted access'() { |
| 42 | + def person = [name: 'John'] |
| 43 | + |
| 44 | + def myNameIs = "I'm $person.name, and you?".toString() |
| 45 | + |
| 46 | + Assert.assertEquals("I'm John, and you?", myNameIs) |
| 47 | + } |
| 48 | + |
| 49 | + @Test |
| 50 | + void 'placeholder with method call'() { |
| 51 | + def name = 'John' |
| 52 | + |
| 53 | + def result = "Uppercase name: ${name.toUpperCase()}".toString() |
| 54 | + |
| 55 | + Assert.assertEquals("Uppercase name: JOHN", result) |
| 56 | + } |
| 57 | + |
| 58 | + |
| 59 | + @Test |
| 60 | + void 'GString and String hashcode'() { |
| 61 | + def string = "2+2 is 4" |
| 62 | + def gstring = "2+2 is ${4}" |
| 63 | + |
| 64 | + Assert.assertTrue(string.hashCode() != gstring.hashCode()) |
| 65 | + } |
| 66 | + |
| 67 | +} |
0 commit comments