SlideShare a Scribd company logo
MAKING JAVA WEB-APPS 
GROOVY 
GROOVY FOR FUN AND PLEASURE. 
by Franjo Žilić
TODAY 
Groovy vs. Java 
Spring with Groovy 
Testing with Groovy 
More testing with Groovy
http://groovy.codehaus.org 
Groovy is a dynamic language of JVM which adds features to 
well known Java syntax and JDK libraries inspired by languages 
like Python, Ruby, Smalltalk.
... 
Makes Java code simpler and easier to read. 
Interoperable with Java libraries. 
Compiles into Java bytecode. 
Let's you get more done by doing less. 
Types are optional or checked.
SOME DIFFERENCES 
default imports 
semicolons are optional 
return is optional 
== means .equals 
getters and setters appear on their own 
public by default 
truth is not what it was 
parentheses are optional * but we like them
REAL TIME SAVERS 
iteration methods 
operators 
null safe dereference - ?. 
elvis - ?: 
spread - *. 
regex - =~ ==~ 
subscript - b[0]
WHY GROOVY IN WEB APP? 
Thought before syntax. 
Easy to learn *if we know Java 
Less code - fewer errors. 
Less code - more tests.
WHY NOT GRAILS 
Rewriting takes time. 
Taking small steps. 
Whole new ecosystem? 
Being forced?
INTEGRATION 
Ant 
Maven 
Gradle
ANT 
Native groovyc integration 
Supports any Groovy version 
Uses stubs for joint (Java+Groovy) projects 
... uses ant
MAVEN 
GMAVENPLUS 
Supports any Groovy version 
Not a native maven-compiler plugin 
Poor IDE integration (Eclipse) 
Uses stubs...
MAVEN 
GROOVY ECLIPSE COMPILER 
Native maven-compiler-plugin 
Good IDE integration (Eclipse, IntelliJ) 
Restricts Groovy version 
No support for invoke-dynamic
GRADLE 
Uses groovyc ant task, so applies as for ant 
Decent IDE integration
SAVING TIME IN PRODUCTION CODE 
Let's say we have a model 
... we can't change it 
... we get a list of UglyJavaModel objects 
... anything can be null
REQUIREMENTS 
someone said: 
count with theAllImportantBoolean true 
top three sorted by someMonetaryValue descending
JAVA 
Let's just count those they want 
final List<UglyJavaModel> list = thirdPartyService.onlyWayToGetData(); 
int countOfThoseWithBooleanTrue = 0; 
for (final UglyJavaModel uglyJavaModel : list) { 
if (uglyJavaModel.getNested() != null 
&& uglyJavaModel.getNested().getNested() != null 
&& uglyJavaModel.getNested().getNested().getNested() != null 
&& uglyJavaModel.getNested().getNested().getNested() 
.getTheAllImportantBoolean() == true) { 
countOfThoseWithBooleanTrue++; 
} 
} model.addAttribute("countWithBooleanTrue", countOfThoseWithBooleanTrue); 
Java can do better, but...
JAVA 
And just top three 
final List<UglyJavaModel> list = thirdPartyService.onlyWayToGetData(); 
list.sort(new Comparator<UglyJavaModel>() { 
@Override 
public int compare(final UglyJavaModel left, final UglyJavaModel right) { 
return left.getNested().getSomeMonetaryValue() 
.compareTo(right.getNested().getSomeMonetaryValue()) * -1; 
} 
}); 
final List<String> topThree = new ArrayList<String>(3); 
for (final UglyJavaModel uglyJavaModel : list.subList(0, 3)) { 
topThree.add(uglyJavaModel.getSomeName()); 
} model.addAttribute("topThree", topThree);
GROOVY 
I know, this is boring 
def list = thirdPartyService.onlyWayToGetData() 
model.addAttribute("countWithBooleanTrue", list.count { 
it?.nested?.nested?.nested?.theAllImportantBoolean 
}) 
model.addAttribute("topThree", list.sort { 
a, b -> 
b.nested.someMonetaryValue <=> a.nested.someMonetaryValue 
}[0..2]*.someName)
TESTING 
JUnit is good enough 
... but we still have to write a lot of code 
... and we need a lot of libraries
WHY GROOVY 
simpler asserts 
dynamic groovy 
less code
CLASSIC JUNIT4 TEST 
@RunWith(MockitoJUnitRunner.class) //omitted imports - Mockito, Assertions 
public class TipicalJunitTest { 
@Test //ommited mocks and prepare data 
public void testUglyJavaControllerReturingCorrectCount() { 
final UglyJavaController controller = new UglyJavaController(service); 
final ArrayList<UglyJavaModel> uglyJavaModels = prepareData(); 
when(service.onlyWayToGetData()).thenReturn(uglyJavaModels); 
final String view = controller.showSomething(model); 
assertThat(view).isEqualTo("ugly"); 
verify(model).addAttribute(eq("countWithBooleanTrue"), eq(1)); 
verify(model).addAttribute(eq("topThree"), captor.capture()); 
verify(service).onlyWayToGetData(); 
verifyNoMoreInteractions(service, model); 
assertThat(captor.getValue()).containsExactly("first","third","second"); 
} 
}
SAME TEST, GROOVY WAY 
class GroovyJunitTest { 
def data = [/* prepare data*/] // use mocks if you want 
@Test 
void testUglyJavaControllerReturingCorrectCount() { 
def controller = new UglyJavaController([onlyWayToGetData: { 
return data }] as ThirdPartyService) 
assert controller.showSomething([addAttribute: { String attr, value -> 
if (attr == 'countWithBooleanTrue') { 
assert value == 1 
} else if (attr == 'topThree') { 
assert value == ['first', 'third', 'second'] 
} else { 
assert false 
} 
}] as Model) == 'ugly' 
} 
}
DATA DRIVEN TESTS 
... the dreaded Parameterized runner 
What about data driven with Spring context? 
No out of the box solution.
WELCOME SPOCK 
... an expressive testing and specification framework 
brings new meaning to data driven 
Written in Groovy, inspired by others*, compatible with JUnit 
*JUnit, jMock, Mockito, RSpec...
@ContextConfiguration(['classpath:spring/test-config.xml']) 
class SneakPeekSpockSpecification extends Specification { 
@Autowired 
SimpleSpringService service 
@Unroll 
void "just a simple sneak peak for spock"() { 
given: 
def testService = new SpockDemoService(service) 
expect: "dependencies are met" 
service 
when: "calculate average for #booleanValue #givenValues.inspect()" 
def average = testService.averageValueFor(booleanValue, givenValues.collect { 
return new UglyJavaModel(nested: 
new UglyJavaModelNested(someMonetaryValue: it.d, nested: 
new UglyJavaModelNestedNested(nested: 
new UglyJavaModelNestedNestedNested(theAllImportantBoolean: it.b)))) 
}) 
then: "average value should be #expected" 
average == expected 
where: 
booleanValue|givenValues || expected 
true |[[b:true,d:42.98],[b:false,d:4.3],[b:true,d:27.31]]||35.14 
false |[[b:true,d:42.98],[b:false,d:4.3],[b:true,d:27.31]]||4.3 
true |[[b:true,d:42.98],[b:true,d:4.3],[b:true,d:27.31]] ||24.86 
} 
}
https://github.com/fzilic/making-java-groovy 
QUESTIONS?

More Related Content

PDF
Javantura v2 - All Together Now - making Groovy and Scala sing together - Din...
PDF
Kotlin advanced - language reference for android developers
PDF
ADG Poznań - Kotlin for Android developers
PDF
A Re-Introduction to JavaScript
PDF
GKAC 2015 Apr. - RxAndroid
PDF
Intro to RxJava/RxAndroid - GDG Munich Android
PPT
A Deeper look into Javascript Basics
PDF
Practical RxJava for Android
Javantura v2 - All Together Now - making Groovy and Scala sing together - Din...
Kotlin advanced - language reference for android developers
ADG Poznań - Kotlin for Android developers
A Re-Introduction to JavaScript
GKAC 2015 Apr. - RxAndroid
Intro to RxJava/RxAndroid - GDG Munich Android
A Deeper look into Javascript Basics
Practical RxJava for Android

What's hot (20)

PDF
RxJava for Android - GDG DevFest Ukraine 2015
ODP
Ast transformations
PPTX
Mastering Java Bytecode With ASM - 33rd degree, 2012
PDF
Javascript basic course
PPT
JavaScript Basics
PDF
Fundamental JavaScript [UTC, March 2014]
PDF
Scala coated JVM
PDF
RxJava on Android
PDF
Bytecode manipulation with Javassist and ASM
PPTX
Kotlin is charming; The reasons Java engineers should start Kotlin.
PDF
Reactive programming on Android
PDF
Advanced javascript
PDF
Java Bytecode for Discriminating Developers - JavaZone 2011
PPTX
Intro to Javascript
PPTX
Club of anonimous developers "Refactoring: Legacy code"
PPT
Basic Javascript
ODP
How to unit test your React/Redux app
PPTX
Unit testing concurrent code
PPTX
Javascript basics for automation testing
ODP
Groovy AST Transformations
RxJava for Android - GDG DevFest Ukraine 2015
Ast transformations
Mastering Java Bytecode With ASM - 33rd degree, 2012
Javascript basic course
JavaScript Basics
Fundamental JavaScript [UTC, March 2014]
Scala coated JVM
RxJava on Android
Bytecode manipulation with Javassist and ASM
Kotlin is charming; The reasons Java engineers should start Kotlin.
Reactive programming on Android
Advanced javascript
Java Bytecode for Discriminating Developers - JavaZone 2011
Intro to Javascript
Club of anonimous developers "Refactoring: Legacy code"
Basic Javascript
How to unit test your React/Redux app
Unit testing concurrent code
Javascript basics for automation testing
Groovy AST Transformations
Ad

Viewers also liked (20)

PDF
Javantura v2 - Telenor banka - Robert Mihaljek, Slavko Žnidarić, Jerko Perleta
PDF
Javantura v2 - Dock your apps - Tomislav Klišanić, Matija Folnović
PDF
Javantura v2 - S-CASE: Towards semi-automated software development - Marin Orlić
PDF
Javantura v2 - Story asynchronous Spring servlets about - Karlo Novak
PDF
Javantura v2 - DigMap - digital map excerpt as a National Spatial Data Infras...
PDF
Javantura v2 - Data modeling with Apapche Cassandra - Marko Švaljek
PDF
Javantura v2 - Replication with MongoDB - what could go wrong... - Philipp Krenn
PDF
Javantura v2 - JavaFX: Write once, run anywhere with RoboVM & DalvikVM - Robe...
PDF
Javantura Zagreb 2014 - Google Dart - Željko Kunica
PDF
Javantura Zagreb 2014 - Nashorn - Miroslav Rešetar
PDF
Javantura Zagreb 2014 - Alfresco-Neo4j integracija - Damir Murat
PDF
Javantura Zagreb 2014 - universAAL - Andrej Grgurić
PDF
Javantura Zagreb 2014 - WildFly 8 - Tomaž Cerar
PDF
PDF
Javantura Zagreb 2014 - Vert.x 1.3 - Mihovil Rister
PDF
Javantura Zagreb 2014 - Groovy-SQL - Dinko Srkoč
PDF
Javantura Zagreb 2014 - Sencha Touch - Denis Jajčević
PDF
Javantura Zagreb 2014 - Java na klijenstskoj strani - Ivan Vučak
PDF
Javantura v2 - The Road to Java - HUJAK & Oracle Croatia - Branko Mihaljević,...
Javantura v2 - Telenor banka - Robert Mihaljek, Slavko Žnidarić, Jerko Perleta
Javantura v2 - Dock your apps - Tomislav Klišanić, Matija Folnović
Javantura v2 - S-CASE: Towards semi-automated software development - Marin Orlić
Javantura v2 - Story asynchronous Spring servlets about - Karlo Novak
Javantura v2 - DigMap - digital map excerpt as a National Spatial Data Infras...
Javantura v2 - Data modeling with Apapche Cassandra - Marko Švaljek
Javantura v2 - Replication with MongoDB - what could go wrong... - Philipp Krenn
Javantura v2 - JavaFX: Write once, run anywhere with RoboVM & DalvikVM - Robe...
Javantura Zagreb 2014 - Google Dart - Željko Kunica
Javantura Zagreb 2014 - Nashorn - Miroslav Rešetar
Javantura Zagreb 2014 - Alfresco-Neo4j integracija - Damir Murat
Javantura Zagreb 2014 - universAAL - Andrej Grgurić
Javantura Zagreb 2014 - WildFly 8 - Tomaž Cerar
Javantura Zagreb 2014 - Vert.x 1.3 - Mihovil Rister
Javantura Zagreb 2014 - Groovy-SQL - Dinko Srkoč
Javantura Zagreb 2014 - Sencha Touch - Denis Jajčević
Javantura Zagreb 2014 - Java na klijenstskoj strani - Ivan Vučak
Javantura v2 - The Road to Java - HUJAK & Oracle Croatia - Branko Mihaljević,...
Ad

Similar to Javantura v2 - Making Java web-apps Groovy - Franjo Žilić (20)

PDF
Oscon Java Testing on the Fast Lane
PDF
Cool JVM Tools to Help You Test
PDF
Cool Jvm Tools to Help you Test - Aylesbury Testers Version
PPT
Svcc Groovy Testing
PPT
GTAC Boosting your Testing Productivity with Groovy
PDF
Using the Groovy Ecosystem for Rapid JVM Development
ODP
New Ideas for Old Code - Greach
PDF
Testing Java Code Effectively
PPT
PDF
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
PPT
Boosting Your Testing Productivity with Groovy
PPT
Javaone2008 Bof 5101 Groovytesting
PDF
Make Your Testing Groovy
PPTX
Test Driven In Groovy
PDF
Cucumber on the JVM with Groovy
PDF
Hacking Java - Enhancing Java Code at Build or Runtime
PDF
Groovy On Trading Desk (2010)
PDF
Grooscript in Action SpringOne2gx 2015
PDF
Groovy a Scripting Language for Java
PDF
Groovy Fly Through
Oscon Java Testing on the Fast Lane
Cool JVM Tools to Help You Test
Cool Jvm Tools to Help you Test - Aylesbury Testers Version
Svcc Groovy Testing
GTAC Boosting your Testing Productivity with Groovy
Using the Groovy Ecosystem for Rapid JVM Development
New Ideas for Old Code - Greach
Testing Java Code Effectively
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
Boosting Your Testing Productivity with Groovy
Javaone2008 Bof 5101 Groovytesting
Make Your Testing Groovy
Test Driven In Groovy
Cucumber on the JVM with Groovy
Hacking Java - Enhancing Java Code at Build or Runtime
Groovy On Trading Desk (2010)
Grooscript in Action SpringOne2gx 2015
Groovy a Scripting Language for Java
Groovy Fly Through

More from HUJAK - Hrvatska udruga Java korisnika / Croatian Java User Association (20)

PDF
Java cro'21 the best tools for java developers in 2021 - hujak
PDF
JavaCro'21 - Java is Here To Stay - HUJAK Keynote
PDF
Javantura v7 - Behaviour Driven Development with Cucumber - Ivan Lozić
PPTX
Javantura v7 - The State of Java - Today and Tomowwow - HUJAK's Community Key...
PPTX
Javantura v7 - Learning to Scale Yourself: The Journey from Coder to Leader -...
PDF
JavaCro'19 - The State of Java and Software Development in Croatia - Communit...
PDF
Javantura v6 - Java in Croatia and HUJAK - Branko Mihaljević, Aleksander Radovan
PDF
Javantura v6 - On the Aspects of Polyglot Programming and Memory Management i...
PPTX
Javantura v6 - Case Study: Marketplace App with Java and Hyperledger Fabric -...
PDF
Javantura v6 - How to help customers report bugs accurately - Miroslav Čerkez...
PDF
Javantura v6 - When remote work really works - the secrets behind successful ...
PDF
Javantura v6 - Kotlin-Java Interop - Matej Vidaković
PDF
Javantura v6 - Spring HATEOAS hypermedia-driven web services, and clients tha...
PDF
Javantura v6 - End to End Continuous Delivery of Microservices for Kubernetes...
PPTX
Javantura v6 - Istio Service Mesh - The magic between your microservices - Ma...
PDF
Javantura v6 - How can you improve the quality of your application - Ioannis ...
PDF
Javantura v6 - Automation of web apps testing - Hrvoje Ruhek
PDF
Javantura v6 - Master the Concepts Behind the Java 10 Challenges and Eliminat...
PDF
Javantura v6 - Building IoT Middleware with Microservices - Mario Kusek
PDF
Javantura v6 - JDK 11 & JDK 12 - Dalibor Topic
Java cro'21 the best tools for java developers in 2021 - hujak
JavaCro'21 - Java is Here To Stay - HUJAK Keynote
Javantura v7 - Behaviour Driven Development with Cucumber - Ivan Lozić
Javantura v7 - The State of Java - Today and Tomowwow - HUJAK's Community Key...
Javantura v7 - Learning to Scale Yourself: The Journey from Coder to Leader -...
JavaCro'19 - The State of Java and Software Development in Croatia - Communit...
Javantura v6 - Java in Croatia and HUJAK - Branko Mihaljević, Aleksander Radovan
Javantura v6 - On the Aspects of Polyglot Programming and Memory Management i...
Javantura v6 - Case Study: Marketplace App with Java and Hyperledger Fabric -...
Javantura v6 - How to help customers report bugs accurately - Miroslav Čerkez...
Javantura v6 - When remote work really works - the secrets behind successful ...
Javantura v6 - Kotlin-Java Interop - Matej Vidaković
Javantura v6 - Spring HATEOAS hypermedia-driven web services, and clients tha...
Javantura v6 - End to End Continuous Delivery of Microservices for Kubernetes...
Javantura v6 - Istio Service Mesh - The magic between your microservices - Ma...
Javantura v6 - How can you improve the quality of your application - Ioannis ...
Javantura v6 - Automation of web apps testing - Hrvoje Ruhek
Javantura v6 - Master the Concepts Behind the Java 10 Challenges and Eliminat...
Javantura v6 - Building IoT Middleware with Microservices - Mario Kusek
Javantura v6 - JDK 11 & JDK 12 - Dalibor Topic

Recently uploaded (20)

PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PPTX
sap open course for s4hana steps from ECC to s4
PPTX
Spectroscopy.pptx food analysis technology
PDF
cuic standard and advanced reporting.pdf
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PPT
Teaching material agriculture food technology
PDF
Electronic commerce courselecture one. Pdf
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Review of recent advances in non-invasive hemoglobin estimation
PPTX
MYSQL Presentation for SQL database connectivity
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Mobile App Security Testing_ A Comprehensive Guide.pdf
sap open course for s4hana steps from ECC to s4
Spectroscopy.pptx food analysis technology
cuic standard and advanced reporting.pdf
Diabetes mellitus diagnosis method based random forest with bat algorithm
Dropbox Q2 2025 Financial Results & Investor Presentation
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Teaching material agriculture food technology
Electronic commerce courselecture one. Pdf
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Digital-Transformation-Roadmap-for-Companies.pptx
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Review of recent advances in non-invasive hemoglobin estimation
MYSQL Presentation for SQL database connectivity
MIND Revenue Release Quarter 2 2025 Press Release
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx

Javantura v2 - Making Java web-apps Groovy - Franjo Žilić

  • 1. MAKING JAVA WEB-APPS GROOVY GROOVY FOR FUN AND PLEASURE. by Franjo Žilić
  • 2. TODAY Groovy vs. Java Spring with Groovy Testing with Groovy More testing with Groovy
  • 3. http://groovy.codehaus.org Groovy is a dynamic language of JVM which adds features to well known Java syntax and JDK libraries inspired by languages like Python, Ruby, Smalltalk.
  • 4. ... Makes Java code simpler and easier to read. Interoperable with Java libraries. Compiles into Java bytecode. Let's you get more done by doing less. Types are optional or checked.
  • 5. SOME DIFFERENCES default imports semicolons are optional return is optional == means .equals getters and setters appear on their own public by default truth is not what it was parentheses are optional * but we like them
  • 6. REAL TIME SAVERS iteration methods operators null safe dereference - ?. elvis - ?: spread - *. regex - =~ ==~ subscript - b[0]
  • 7. WHY GROOVY IN WEB APP? Thought before syntax. Easy to learn *if we know Java Less code - fewer errors. Less code - more tests.
  • 8. WHY NOT GRAILS Rewriting takes time. Taking small steps. Whole new ecosystem? Being forced?
  • 10. ANT Native groovyc integration Supports any Groovy version Uses stubs for joint (Java+Groovy) projects ... uses ant
  • 11. MAVEN GMAVENPLUS Supports any Groovy version Not a native maven-compiler plugin Poor IDE integration (Eclipse) Uses stubs...
  • 12. MAVEN GROOVY ECLIPSE COMPILER Native maven-compiler-plugin Good IDE integration (Eclipse, IntelliJ) Restricts Groovy version No support for invoke-dynamic
  • 13. GRADLE Uses groovyc ant task, so applies as for ant Decent IDE integration
  • 14. SAVING TIME IN PRODUCTION CODE Let's say we have a model ... we can't change it ... we get a list of UglyJavaModel objects ... anything can be null
  • 15. REQUIREMENTS someone said: count with theAllImportantBoolean true top three sorted by someMonetaryValue descending
  • 16. JAVA Let's just count those they want final List<UglyJavaModel> list = thirdPartyService.onlyWayToGetData(); int countOfThoseWithBooleanTrue = 0; for (final UglyJavaModel uglyJavaModel : list) { if (uglyJavaModel.getNested() != null && uglyJavaModel.getNested().getNested() != null && uglyJavaModel.getNested().getNested().getNested() != null && uglyJavaModel.getNested().getNested().getNested() .getTheAllImportantBoolean() == true) { countOfThoseWithBooleanTrue++; } } model.addAttribute("countWithBooleanTrue", countOfThoseWithBooleanTrue); Java can do better, but...
  • 17. JAVA And just top three final List<UglyJavaModel> list = thirdPartyService.onlyWayToGetData(); list.sort(new Comparator<UglyJavaModel>() { @Override public int compare(final UglyJavaModel left, final UglyJavaModel right) { return left.getNested().getSomeMonetaryValue() .compareTo(right.getNested().getSomeMonetaryValue()) * -1; } }); final List<String> topThree = new ArrayList<String>(3); for (final UglyJavaModel uglyJavaModel : list.subList(0, 3)) { topThree.add(uglyJavaModel.getSomeName()); } model.addAttribute("topThree", topThree);
  • 18. GROOVY I know, this is boring def list = thirdPartyService.onlyWayToGetData() model.addAttribute("countWithBooleanTrue", list.count { it?.nested?.nested?.nested?.theAllImportantBoolean }) model.addAttribute("topThree", list.sort { a, b -> b.nested.someMonetaryValue <=> a.nested.someMonetaryValue }[0..2]*.someName)
  • 19. TESTING JUnit is good enough ... but we still have to write a lot of code ... and we need a lot of libraries
  • 20. WHY GROOVY simpler asserts dynamic groovy less code
  • 21. CLASSIC JUNIT4 TEST @RunWith(MockitoJUnitRunner.class) //omitted imports - Mockito, Assertions public class TipicalJunitTest { @Test //ommited mocks and prepare data public void testUglyJavaControllerReturingCorrectCount() { final UglyJavaController controller = new UglyJavaController(service); final ArrayList<UglyJavaModel> uglyJavaModels = prepareData(); when(service.onlyWayToGetData()).thenReturn(uglyJavaModels); final String view = controller.showSomething(model); assertThat(view).isEqualTo("ugly"); verify(model).addAttribute(eq("countWithBooleanTrue"), eq(1)); verify(model).addAttribute(eq("topThree"), captor.capture()); verify(service).onlyWayToGetData(); verifyNoMoreInteractions(service, model); assertThat(captor.getValue()).containsExactly("first","third","second"); } }
  • 22. SAME TEST, GROOVY WAY class GroovyJunitTest { def data = [/* prepare data*/] // use mocks if you want @Test void testUglyJavaControllerReturingCorrectCount() { def controller = new UglyJavaController([onlyWayToGetData: { return data }] as ThirdPartyService) assert controller.showSomething([addAttribute: { String attr, value -> if (attr == 'countWithBooleanTrue') { assert value == 1 } else if (attr == 'topThree') { assert value == ['first', 'third', 'second'] } else { assert false } }] as Model) == 'ugly' } }
  • 23. DATA DRIVEN TESTS ... the dreaded Parameterized runner What about data driven with Spring context? No out of the box solution.
  • 24. WELCOME SPOCK ... an expressive testing and specification framework brings new meaning to data driven Written in Groovy, inspired by others*, compatible with JUnit *JUnit, jMock, Mockito, RSpec...
  • 25. @ContextConfiguration(['classpath:spring/test-config.xml']) class SneakPeekSpockSpecification extends Specification { @Autowired SimpleSpringService service @Unroll void "just a simple sneak peak for spock"() { given: def testService = new SpockDemoService(service) expect: "dependencies are met" service when: "calculate average for #booleanValue #givenValues.inspect()" def average = testService.averageValueFor(booleanValue, givenValues.collect { return new UglyJavaModel(nested: new UglyJavaModelNested(someMonetaryValue: it.d, nested: new UglyJavaModelNestedNested(nested: new UglyJavaModelNestedNestedNested(theAllImportantBoolean: it.b)))) }) then: "average value should be #expected" average == expected where: booleanValue|givenValues || expected true |[[b:true,d:42.98],[b:false,d:4.3],[b:true,d:27.31]]||35.14 false |[[b:true,d:42.98],[b:false,d:4.3],[b:true,d:27.31]]||4.3 true |[[b:true,d:42.98],[b:true,d:4.3],[b:true,d:27.31]] ||24.86 } }