Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Enterprise Web App. Development (3): Test Tool Training

Enterprise Web App. Development (3): Test Tool Training

This is the third course of a series of the courses for Enterprise Web Application development based on several Open Source products. As open source development tools, we are going to take care of Apache Maven as a build tool, Git as a version control tool and JUnit5 as a test tool. After then, we are going into the Jakarta EE framework. Therefore this series require the basic skills of Windows 10, CentOS, Eclipse IDE, Java SE (Oracle JDK, Open JDK), Payara Server and PostgreSQL. Regarding the Payara Server, we can use another Web Application Server conforming to Jakarta EE specification. As for PostgreSQL, we might be able to use another RDBMS product instead. We can also make use of another Linux distribution instead of CentOS.

E7d0d73badb1cc1df2bc44f58d51aaff?s=128

Koichi NAKAGAWA

November 26, 2020
Tweet

Transcript

  1. TEST TOOL A part of the Open Source Development Tools

    Using JUnit with JDT™ & M2Eclipse™ Eclipse™ Plug-ins 1 By Koichi NAKAGAWA
  2. Open Source Development Tools Test Tool (JUnit) 2

  3. EWA development course curriculum Object Oriented Development Methodology JSF with

    CDI JPA + JTA with CDI JAX-RS Application Architecture Design Patterns Eclipse IDE™ Version Control Tool with Git™ Build Tool with Apache Maven™ Payara Server™ Administration Windows 10™ + Linux (CentOS™) Total EWA Development Exercise Jakarta Batch Java SE (Oracle JDK™/OpenJDK™) Required Skills to take courses Test Tool with JUnit5 PostgreSQL™ Administration 3
  4. Open Source Development Tools • Build Tool (Apache Maven™ with

    Eclipse™ Plug-in) • Version Control Tool (Git™ with Eclipse™ Plug-in) • Test Tool (JUnit5 with Eclipse™ Plug-in) 4
  5. Trademarks Notice • Eclipse Java development tools™, Java development tools™,

    Eclipse JDT™, JDT™ are trademarks of the Eclipse Foundation. • Eclipse IDE for Enterprise Java Developers™, Eclipse IDE for Enterprise Java Developers™ logo( ) are trademarks of the Eclipse Foundation. • Eclipse m2eclipse™, m2eclipse™ are trademarks of the Eclipse Foundation. • Apache Maven™, Maven™ are trademarks of the Apache Software Foundation (ASF). • Java™ is trademark of Oracle Corporation. 5
  6. Assumption for this course • The trainees who take this

    course are required the following skills in advance • Oracle JDK/OpenJDK (Version: 8) • Eclipse IDE for Enterprise Java Developers (Version: 2020-06 (4.16.0)) • Build Tool Training Course 6
  7. Objectives this course • Learning the JUnit5 Test Tool, you

    will obtain the concepts of test tool and how to operate it through JDT™ Eclipse™ plug-in for JUnit and M2Eclipse™ Eclipse™ plug-in for Apache Maven. You also learn how to perform Java Unit Test, Java Unit Test with Mock, Java CDI Integration Test and Web Application System Test. 7
  8. JUnit Test Tool • Java Test Framework Basics • JUnit

    Concepts • JUnit + Apache Maven™ • Eclipse Java development tools™ Eclipse Plug-in 8
  9. Java Test Framework Basics 9

  10. Target Java Application Components CDI Component What’s Java Testing Framework?

    • Definition of Java Testing Framework Test Application Check Java SE (JDK) • Dependency Injection • Transaction with JTA • Directly Access from JSF, JSP • Several Scoped Contexts • Interceptor (AOP) • Support JavaSE (from CDI 2.0) CDI: A part of Jakarta EE Java Testing Framework Web Component Java Component 10
  11. Testing Types • Unit Test Java Component A Java Test

    Application Check Java Component A Java Test Application Check Java Component B Mock for Java Component B Create Call Simple Unit Test Unit Test with Mock JUnit5 JUnit5 + Mockito-Jupiter Extension Mockito Java SE (JDK) Java SE (JDK) 11
  12. Testing Types • Integration Test CDI Component A CDI Test

    Application Check CDI Component B Integration Test between CDI Components JUnit5 + Weld SE + Weld JUnit 5 Extensions (for CDI Components) Java SE (JDK) 12
  13. Java SE (JDK) Payara Server (Jakarta EE Framework) Testing Types

    • System Test CDI Component A Web Test Application Check CDI Component B System Test for Total Java Application JUnit5 + Selenium + Selenium-Jupiter Extension (for Web Interface Components) Web Component C Java SE (JDK) 13
  14. JUnit Concepts 14

  15. What’s JUnit? • Definition of JUnit JUnit is a simple

    framework to write repeatable tests. It is an instance of the xUnit architecture for unit testing frameworks. (Source: JUnit. “About JUnit4”, https://junit.org/junit4/) JUnit 5 is the next generation of JUnit. The goal is to create an up-to-date foundation for developer-side testing on the JVM. This includes focusing on Java 8 and above, as well as enabling many different styles of testing. JUnit 5 is the result of JUnit Lambda and its crowdfunding campaign on Indiegogo. (Source: JUnit. “About JUnit5”, https://junit.org/junit5/) 15
  16. JUnit 5 • JUnit 5 = JUnit Platform + JUnit

    Jupiter + JUnit Vintage JUnit Platform Java SE (JDK) Launching testing framework foundation (Run TestEngine from IDE like Eclipse™ and Build Tool like Maven™) TestEngineAPI JUnit Jupiter (TestEngine for JUnit 5) JUnit Vintage (TestEngine for JUnit 3 & 4) JUnit 5 Test Application JUnit 3 & 4 Test Application Launch TestEngine Launch TestEngine 16
  17. JUnit Test Application: Test class and test • Test class

    and method public class XyzTest { : @Test public void funcTest1() { : assertXXXX(); } @Test public void funcTest2() { : } : } Test class : - Definition: Java Class including Test methods. - Naming Convention: xxxTest (Apache Maven™ automatically detect Test classes which have “Test” as its suffix to put it in its “test scope”.) Test method: - Definition: Java Method annotated with @Test inside Test class. - Validation: “assert” methods are used inside to validate the test results. - Naming Convention: meaningful names should be used to be understood easily. - Execution Order: Arbitrary order (Any test should not be dependent on each other.) Test Method Test Method Test class . . . Assertions: Judge whether this test method finished successfully or not. 17
  18. JUnit: Annotations for test • Useful Annotations for test (1)

    Annotation Meaning @Test Identifies a method as a test method. @Before (JUnit4) @BeforeEach (JUnit5) Executed before each test. It is used to prepare the test environment (e.g., read input data, initialize the class). @After (JUnit4) @AfterEach (JUnit5) Executed after each test. It is used to cleanup the test environment (e.g., delete temporary data, restore defaults). It can also save memory by cleaning up expensive memory structures. @BeforeClass (JUnit4) @BeforeAll (JUnit5) Executed once, before the start of all tests. It is used to perform time intensive activities, for example, to connect to a database. Methods marked with this annotation need to be defined as static to work with JUnit. @AfterClass (JUnit4) @AfterAll (JUnit5) Executed once, after all tests have been finished. It is used to perform clean-up activities, for example, to disconnect from a database. Methods annotated with this annotation need to be defined as static to work with JUnit. 18
  19. JUnit: Annotations for test • Useful Annotations for test (2)

    Annotation Meaning @Ignore(["Why disabled“]) (JUnit4) @Disabled([“Why disabled”]) (JUnit5) Marks that the test should be disabled. This is useful when the underlying code has been changed and the test case has not yet been adapted. With JUnit5, assumeTrue() or assumeFalse() asserts can be also used to disable the test, when a condition is false or true respectively. @Test (expected = Exception.class) (JUnit4) Fails if the method does not throw the named exception. With JUnit5, assertThrows() assert can be used for this purpose. @Test(timeout=100) (JUnit4) Fails if the method takes longer than a specified value in milliseconds. With JUnit5, assertTimeout() assert can be used for this purpose. @DisplayName(“message”) (JUnit5) Declare a custom display name for the annotated test class or test method. 19
  20. JUnit: Asserts for test • Useful Asserts for test (1)

    Assert Meaning fail([message]) Let the method fail. Might be used to check that a certain part of the code is not reached or to have a failing test before the test code is implemented. The message parameter is optional. assertTrue([message,] boolean condition) Checks that the boolean condition is true. assertFalse([message,] boolean condition) Checks that the boolean condition is false. assertEquals([message,] expected, actual) Tests that two values are the same. Note: for arrays the reference is checked, not the content of the arrays. assertEquals([message,] expected, actual, tolerance) Test that float or double values match. The tolerance is the number of decimals which must be the same. 20
  21. JUnit: Asserts for test • Useful Asserts for test (2)

    Assert Meaning assertNull([message,] object) Checks that the object is null. assertNotNull([message,] object) Checks that the object is not null. assertSame([message,] expected, actual) Checks that both variables refer to the same object. assertNotSame([messag e,] expected, actual) Checks that both variables refer to different objects. 21
  22. Java Unit Test • Check if a target class works

    correctly import static org.junit.jupiter.api.Assertions.assertXXX; import org.junit.jupiter.api.Test; public class XXXTest { @Test public void yyy() { : : assertXXX(); } } XXXTest.java Check if Component A worked correctly with assertions. In case of JUnit5Test Application Test Class Test Method Java Component A Java Test Application JUnit Java SE (JDK) Test Code for Component A 22
  23. Java Unit Test Example • Let’s make a JUnit Test

    program for Java Unit Test Check if the “evaluate” method of “Calculate” class works correctly public class Calculator { public int evaluate(String expression) { int sum = 0; for (String summand: expression.split("\\+")) sum += Integer.valueOf(summand); return sum; } } Calculator.java Target Test Class 23 Exercise: Let’s write a Java Test Application for the above Target Class.
  24. Java Unit Test Exercise • Sample JUnit Test program for

    Java Unit Test import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; public class CalculatorTest { @Test public void evaluatesExpression() { Calculator calculator = new Calculator(); int sum = calculator.evaluate("1+2+3"); assertEquals(6, sum); } } CalculatorTest.java Check if the sum of “1+2+3” is “6”. 24
  25. Java Unit Test with Mock • Check if a target

    class works correctly using Mock technology @ExtendWith(MockitoExtension.class) public class XXXTest { @Mock ComponentB compB; @InjectMocks ComponentA compA; @Test public void funcTest1() { when(compB.func1()).thenReturn(new ComponentB()); compA.funcA(); : } } XXXTest.java Java Component A Java Test Application Check Java Component B Mock for Java Component B Create Call JUnit + Mockito-Jupiter Extension Mockito Java SE (JDK) Mocked Component Component Injecting Mocked Component Specify when a method of Mocked Component is called, what is returned. Extend with Mockito Extension When ComponentB#func1() is called inside ComponentA#funcA(), an instance of ComponentB is returned. 25
  26. Java Unit Test with Mock Example • Let’s make a

    JUnit Test program for Java Unit Test using Mock Check if the “add” method of “Score” class works correctly by mocking “Calculator” class public class Calculator { public int evaluate(String expression) { int sum = 0; for (String summand: expression.split("\\+")) sum += Integer.valueOf(summand); return sum; } } Calculator.java public class Score { private Calculator calc; public int add(String expA, String expB) { int sum = calc.evaluate(expA) + calc.evaluate(expB); return sum; } } Score.java Target Test Class 26 Exercise: Let’s write a Java Test Application for the above Target Test Class.
  27. Java Unit Test with Mock Example • Sample JUnit Test

    program for Java Unit Test with Mock @ExtendWith(MockitoExtension.class) public class ScoreTest { @Mock Calculator calc; @InjectMocks Score score; @Test public void testAdd() { when(calc.evaluate(anyString())).thenReturn(5); int sum = score.add(“1+4”, “1+2+2”); assertEquals(10, sum); } : } ScoreTest.java 27
  28. Java CDI Integration Test • Check if a target CDI

    class works correctly communicating with other CDI classes @EnableWeld public class XXXTest { @WeldSetup public WeldInitiator weld = WeldInitiator.from(ComponentA.class, ComponentB.class) .activate(RequestScoped.class, ApplicationScoped.class).build(); @Inject ComponentA compA ; @Test public void funcTest1() { : assertXXX(…); } } XXXTest.java Enable Weld SE with Weld JUnit 5 Extension Initialize Weld SE with CDI components Inject the target CDI component Test the target CDI component CDI Component A <RequestScoped> CDI Test Application Check CDI Component B <ApplicationScoped> JUnit + Weld SE + Weld JUnit 5 Extension (for CDI Components) Java SE (JDK) 28
  29. Java CDI Integration Test Example • Let’s make a Junit

    Test program for Java CDI Integration Test  Check if the “add()” method of “Score” class works correctly along with “Calculator” class @RequestScoped public class Calculator { public int evaluate(String expression) { int sum = 0; for (String summand: expression.split("\\+")) sum += Integer.valueOf(summand); return sum; } } Calculator.java @RequestScoped public class Score { @Inject private Calculator calc; public int add(String expA, String expB) { int sum = calc.evaluate(expA) + calc.evaluate(expB); return sum; } } Score.java Target Test Class 29 Exercise: Let’s write a Java Test Application for the above Target Test Class.
  30. Java CDI Integration Test Example • Sample JUnit Test program

    for Java CDI Integration Test @EnableWeld public class ScoreTest { @WeldSetup public WeldInitiator weld = WeldInitiator.from (Score.class, Calculator.class) .activate(RequestScoped.class, RequestScoped.class).build(); @Inject Score score; @Test public void testAdd() { int sum = score.add(“1+2+3”, “3+6”); assertEquals(15, sum); } } ScoreTest.java 30
  31. Java Web System Test • Check if a target Web

    Component works correctly communicating with other CDI classes @ExtendWith(SeleniumExtension.class) public class XXXIT { @Test public void testChrome(ChromeDriver driver) { driver.get(“<Application URL ex. http://localhost:8080/app/>"); WebElement element = driver.findElement(By.id(“<HTML Id for input>")); element.sendKeys(“Input Data"); element = driver.findElement(By.id(“<HTML Id for submit>")); element.click(); assertThat(driver.getTitle(), startsWith(“<HTML Title>")); } } XXXIT.java Enable Selenium-Jupiter JUnit5 Extension Inject Chrome Driver Search for a web element Click a button Java SE (JDK) Payara Server (Jakarta EE Framework) CDI Component A Web Test Application Check CDI Component B JUnit + Selenium + Selenium-Jupiter Extension (for Web Interface Components) Web Component C Java SE (JDK) Enter some data in the web element 31
  32. Java Web System Test Example • Let’s make a JUnit

    Test program for Java Web System Test Check if the “Calculate” button of a JSF menu works correctly @RequestScoped public class Calculator { public int evaluate(String expression) { int sum = 0; for (String summand: expression.split("\\+")) sum += Integer.valueOf(summand); return sum; } } Calculator.java @ReuqestScoped @Named public class Score { @Inject private Calculator calc; private String expA, expB, expSum; public void add() { int sum = calc.evaluate(expA) + calc.evaluate(expB); expSum = new Integer(sum).toString(); } } Score.java CDI Bean for JSF A: (Id: expA) B: (Id: expB) = (Id: expSum) + Calculate Accessors are required Web menu using JSF (URL: http://localhost:8080/app/) (Id: calculate) Bind Target Web Menu 32 Exercise: Let’s write a Java Test Application for the above Target Web Component.
  33. Java Web System Test Example • Sample JUnit Test program

    for Java Web System Test @ ExtendWith(SeleniumExtension.class) public class ScoreIT { @Test public void testAdd(ChromeDriver driver) throws InterruptedException{ driver.get(“http://localhost:8080/app/"); WebElement element = driver.findElement(By.id(“expA")); element.sendKeys(“1+2+3"); element = driver.findElement(By.id(“expB")); element.sendKeys(“5+7+9"); element = driver.findElement(By.id(“calculate")); element.click(); Thread.sleep(5000); element = driver.findElement(By.id(“expSum")); assertEquals(“27”, element.getText()); } } ScoreIT.java 33 ChromeDriver is automatically downloaded over internet and stored into the Maven local repository at its “integration-test” phase.
  34. JUnit + Apache Maven™ 34

  35. Apache Maven™ Build Life Cycle • Test Phase of Apache

    Maven™ Build Life Cycle Compile Test Package Integration Test Install Deploy • Java Unit Test • Java Unit Test with Mock • CDI Integration Test maven-surefire-plugin 35
  36. Unit Test with JUnit + Apache Maven™ • Location of

    Test Programs using Apache Maven™ Project src main test target pom.xml Package Folders xxxTest.java “maven-surefire-plugin” fetches these classes as test class. 36
  37. Java Unit Test • pom.xml for JUnit Test Application (1)

    ... <build> <plugins> <plugin> <artifactId>maven-surefire-plugin</artifactId> <version>2.22.2</version> </plugin> </plugins> </build> ... From 2.22.0, maven-surefire-plugin supports JUnit Platform (JUnit5) natively. 37
  38. Java Unit Test • pom.xml for JUnit Test Application (2)

    <dependencies> ... <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13</version> <scope>test</scope> </dependency> <dependency> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> <version>5.7.0</version> <scope>test</scope> </dependency> ... </dependencies> <dependencies> ... <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-api</artifactId> <version>5.7.0</version> <scope>test</scope> </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-engine</artifactId> <version>5.7.0</version> <scope>test</scope> </dependency> ... (continued…) For JUnit4 Application For JUnit5 Application 38
  39. Java Unit Test • pom.xml for JUnit Test Application (3)

    ... <dependency> <groupId>org.hamcrest</groupId> <artifactId>hamcrest</artifactId> <version>2.2</version> <scope>test</scope> </dependency> ... </dependencies> For JUnit5 Application Including useful Assertions which are bundled in JUnit4 APIs 39
  40. Java Unit Test with Mock • pom.xml for JUnit Test

    Application with Mockito <dependencies> ... <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-core</artifactId> <version>3.6.0</version> <scope>test</scope> </dependency> <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-junit-jupiter</artifactId> <version>3.6.0</version> <scope>test</scope> </dependency> ... </dependencies> Including Mockito Core functionalities Including Mockito Extension for JUnit5 For JUnit5 Application 40
  41. Java CDI Integration Test • pom.xml for CDI Integration Test

    Application with Weld JUnit5 Extension <dependencies> ... <dependency> <groupId>org.jboss.weld</groupId> <artifactId>weld-junit5</artifactId> <version>2.0.1.Final</version> <scope>test</scope> </dependency> <dependency> <groupId>org.jboss.weld.se</groupId> <artifactId>weld-se-core</artifactId> <version>3.1.5.Final</version> </dependency> ... </dependencies> Including Weld-JUnit5 functionalities For JUnit5 Application 41
  42. Apache Maven™ Build Life Cycle • Integration Test Phase of

    Apache Maven™ Build Life Cycle Compile Test Package Integration Test Install Deploy • Web System Test with Selenium-Jupiter maven-failsafe-plugin 42
  43. System Test with JUnit + Apache Maven™ • Location of

    Integration Test Programs using Apache Maven™ Project src main test target pom.xml Package Directories xxxIT.java “maven-failsafe-plugin” fetches these classes as integration test class. 43
  44. Web System Test • pom.xml for Web System Test Application

    with Selenium-Jupiter JUnit5 Extension (1) <dependencies> ... <dependency> <groupId>io.github.bonigarcia</groupId> <artifactId>selenium-jupiter</artifactId> <version>3.3.5</version> <scope>test</scope> </dependency> ... </dependencies> Including Selenium-Jupiter functionalities 44
  45. Web System Test • pom.xml for Web System Test Application

    with Selenium-Jupiter JUnit5 Extension (2) <build> <plugins> : <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-failsafe-plugin</artifactId> <version>2.22.2</version> <executions> <execution> <id>perform-it</id> <goals> <goal>integration-test</goal> </goals> </execution> </executions> </plugin> : </plugins> </build> Take care of tests in “Integration Test” phase of Maven life-cycle 45
  46. Eclipse Java development tools™ Eclipse Plug-in 46

  47. Eclipse Java development tools™ (JDT™) • JDT™ Eclipse Plug-in JDT™

    includes JUnit Plug-in for Eclipse and is bundled into Eclipse IDE for Enterprise Java Developers™ 47
  48. How to execute Tests with Eclipse™ • Execute JUnit directly

    from Eclipse  Right click on the project  Run As  2 JUnit Test 48
  49. How to execute Tests with Eclipse™ • Execute JUnit through

    M2Eclipse™ (Eclipse™ plugin for Apache Maven™) Right click on the project  Run As 4 Maven build … Build Name Goal Name Profile Name Ex. clean package, integration-test Ex. payara5x-local, payara5x-remote 49
  50. Development Environment Configuration • Create a new Eclipse™ workspace and

    configure “Installed JREs” for the workspace 50 Eclipse™ Workspace C:\Users\<User Id>\eclipse-workspace\ws3 Configure “Installed JREs” Exercise: Let’s create a new Eclipse™ workspace and configure “Installed JREs” for the workspace with the above information.
  51. Java Unit Test Exercise • Create a new Eclipse™ Workspace

    named “ws3”.  Click “File”  “Switch Workspace”  “Other…”  Fill in the new workspace folder path of “ws3” and click “Launch” button. C:\Users\<User Id>\eclipse-workspace\ws3 51
  52. • Configure Installed JREs (1) 1. Select “Window  Preferences”

    and “Preferences” dialog menu comes up. 2. Select “Java  Installed JREs” and click “Add …” button. 52 Java Unit Test Exercise
  53. • Configure Installed JREs (2) 3. Select “Standard VM” and

    click “Next >” button and “Add JRE” dialog menu comes up. 4. Click “Directory …” button and select an installed JDK home directory and click “Finish” button. 53 Java Unit Test Exercise
  54. • Configure Installed JREs (3) 5. Select the added JDK

    entry from a list of “Installed JREs” and click “Apply and Close” button. 54 Java Unit Test Exercise
  55. Java Unit Test Example • Check if the “evaluate()” method

    of “Calculator” class works correctly public class Calculator { public int evaluate(String expression) { int sum = 0; for (String summand: expression.split("\\+")) sum += Integer.valueOf(summand); return sum; } } Calculator.java Target Class 55 Exercise: Let’s make a Java Unit Test Application to test the “evaluate()” method of the “Calculator” class with the above information.
  56. Java Unit Test Exercise • Procedure of the Exercise Make

    a Project and edit pom.xml Make the Calculator Java Class Make a JUnit Test Class for the Calculator Execute JUnit from Eclipse Execute JUnit from Maven 56
  57. Java Unit Test Exercise • Procedure of the Exercise Make

    a Project and edit pom.xml Make the Calculator Java Class Make a JUnit Test Class for the Calculator Execute JUnit from Eclipse Execute JUnit from Maven 57
  58. Java Unit Test Exercise • Create a new Eclipse™ Project

    named “test1” (1)  Click “Create a Maven project” in Project Explorer 58
  59. Java Unit Test Exercise • Create a new Eclipse™ Project

    named “test1” (2)  Confirm “Use default Workspace location” is selected and click “Next >” button.  Enter “maven-archetype-simple” in the “Filter” field and select an archetype of “org.apache.maven.archetypes maven-archetype-simple 1.4” and then click “Next >” button. 59
  60. Java Unit Test Exercise • Create a new Eclipse™ Project

    named “test1” (3)  From “New Maven project” dialog menu, Enter a Group Id of “org.example” and a Artifact Id of “test1” and a Version of “0.0.1” and click “Finish” button. 60
  61. Java Unit Test Exercise • Modify the created Maven Object

    Model file (pom.xml)  Change the compiler version to “1.8”.  Change the version of “maven-surefire-plugin” to “2.22.2” and delete other plug-ins.  Add “junit-jupiter-api”, “junit-jupiter-engine” and “hamcrest” as dependency and delete “junit”. <dependencies> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-api</artifactId> <version>5.7.0</version> <scope>test</scope> </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-engine</artifactId> <version>5.7.0</version> <scope>test</scope> </dependency> <build> <pluginManagement> <plugins> <plugin> <artifactId>maven-surefire-plugin</artifactId> <version>2.22.2</version> </plugin> </plugins> </pluginManagement> </build> <properties> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> </properties> <dependency> <groupId>org.hamcrest</groupId> <artifactId>hamcrest</artifactId> <version>2.2</version> <scope>test</scope> </dependency> </dependencies> 61
  62. Java Unit Test Exercise • Procedure of the Exercise Make

    a Project and edit pom.xml Make the Calculator Java Class Make a JUnit Test Class for the Calculator Execute JUnit from Eclipse Execute JUnit from Maven 62
  63. Java Unit Test Exercise • Created a Java source file

    named “Calculator.java”  Right click on the package of “org.example.test1” under “src/main/java” and select “New”  “Class”.  Fill “Calculate” in Name field and click “Finish” button. 63
  64. Java Unit Test Exercise • Modify the created Java source

    file (Calculator.java)  In the “Calculator” class, add a method of “evaluate(String expression)”. package org.example.test1; public class Calculator { public int evaluate(String expression) { int sum = 0; for (String summand: expression.split("\\+")) sum += Integer.valueOf(summand); return sum; } } 64
  65. Java Unit Test Exercise • Procedure of the Exercise Make

    a Project and edit pom.xml Make the Calculator Java Class Make a JUnit Test Class for the Calculator Execute JUnit from Eclipse Execute JUnit from Maven 65
  66. Java Unit Test Exercise • Create a Test Class file

    for the created Java source file named “CalculateTest.java”  Right click on the package of “org.example.test1” under “src/test/java” and select “New”  “Other…”.  Select “Java”  “JUnit”  “JUnit Test Case” and click “Next >” button 66
  67. Java Unit Test Exercise • Create a Test Class file

    for the created Java source file named “CalculateTest.java” Check if “New JUnit Jupiter test” is selected. Enter “CalculateTest” in the Test Class Name field and click “Finish” button.  Delete “AppTest.ava” of the package of “org.example.test1” under “src/test/java” 67
  68. Java Unit Test Exercise • Modify the created Java Test

    source file (CalculatorTest.java)  In the “CalculatorTest” class, add a method of “evaluateExpression()” with “@Test” annotation. package org.example.test1; import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; class CalculateTest { @Test public void evaluatesExpression() { Calculator calculator = new Calculator(); int sum = calculator.evaluate("1+2+3"); assertEquals(6, sum); } } 68
  69. Java Unit Test Exercise • Update Apache Maven™ Project to

    remove a warning icon on the project. Confirm that there is a warning icon for the project of “test1”. Right click on the project of “test1” and select “Maven”  “Update Project …”.  Select “test1” from Maven Codebases and click “OK” button. 69 Warning Icon Warning Icon is disappeared.
  70. Java Unit Test Exercise • Procedure of the Exercise Make

    a Project and edit pom.xml Make the Calculator Java Class Make a JUnit Test Class for the Calculator Execute JUnit from Eclipse Execute JUnit from Maven 70
  71. Java Unit Test Exercise • Execute JUnit directly for the

    created Java Test source file  Right click on the project and select “Run As”  “JUnit Test”  Confirm that JUnit finished successfully showing “Green” flag. 71
  72. Java Unit Test Exercise • If we got an error

    like the above Error Dialog, change the configuration of JUnit Test  Right click on the project and select “Run As”  “Run Configurations…”  Select “JUnit  test1” and change the “Test runner” to “JUnit 5” and click “Run” button. 72 Error Dialog
  73. Java Unit Test Exercise • Procedure of the Exercise Make

    a Project and edit pom.xml Make the Calculator Java Class Make a JUnit Test Class for the Calculator Execute JUnit from Eclipse Execute JUnit from Maven 73
  74. Java Unit Test Exercise • Execute JUnit through M2Eclipse™ for

    the created Java Test source file  Right click on the project and select “Run As”  “Maven build”  Put “test1 – package” in “Name” field and “clean package” in “Goals” field and click “Run” button.  Confirm that test completes successfully in “Console” 74
  75. Java Unit Test with Mock Example • Check if the

    “add” method of “Score” class works correctly by mocking “Calculator” class public class Calculator { public int evaluate(String expression) { int sum = 0; for (String summand: expression.split("\\+")) sum += Integer.valueOf(summand); return sum; } } Calculator.java public class Score { private Calculator calc; public int add(String expA, String expB) { int sum = calc.evaluate(expA) + calc.evaluate(expB); return sum; } } Score.java Target Class Mocked Class 75 Exercise: Let’s make a Java Unit Test Application to test the “add()” method of the “Score” class by mocking the “Calculator” class with the above information.
  76. Java Unit Test with Mock Exercise • Procedure of the

    Exercise Edit pom.xml Make the Score Java Class Make a JUnit Test Class for the Score Execute JUnit from Eclipse Execute JUnit from Maven 76
  77. Java Unit Test with Mock Exercise • Modify the Maven

    Object Model file (pom.xml) Add “mockito-core”and “mockito-junit-jupiter” as dependency. <dependencies> : <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-core</artifactId> <version>3.6.0</version> <scope>test</scope> </dependency> <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-junit-jupiter</artifactId> <version>3.6.0</version> <scope>test</scope> </dependency> : </dependencies> 77
  78. Java Unit Test with Mock Exercise • Procedure of the

    Exercise Edit pom.xml Make the Score Java Class Make a JUnit Test Class for the Score Execute JUnit from Eclipse Execute JUnit from Maven 78
  79. Java Unit Test with Mock Exercise • Created a Java

    source file named “Score.java”  Right click on the package of “org.example.test1” under “src/main/java” and select “New”  “Class”.  Fill “Score” in Name field and click “Finish” button. 79
  80. Java Unit Test with Mock Exercise • Modify the created

    Java source file (Score.java)  In the “Score” class, add a method of “add(String expA, String expB)”. package org.example.test1; public class Score { private Calculator calc; public int add(String expA, String expB) { int sum = calc.evaluate(expA) + calc.evaluate(expB); return sum; } } 80
  81. Java Unit Test with Mock Exercise • Procedure of the

    Exercise Edit pom.xml Make the Score Java Class Make a JUnit Test Class for the Score Execute JUnit from Eclipse Execute JUnit from Maven 81
  82. Java Unit Test with Mock Exercise • Create a Test

    Class file for the created Java source file named “ScoreTest.java”  Right click on the package of “org.example.test1” under “src/test/java” and select “New”  “Other…”.  Select “Java”  “JUnit”  “JUnit Test Case” and click “Next >” button 82
  83. Java Unit Test with Mock Exercise • Create a Test

    Class file for the created Java source file named “ScoreTest.java”  Fill “ScoreTest” in the Test Class Name field and click “Finish” button. 83
  84. Java Unit Test with Mock Exercise • Modify the created

    Java Test source file (ScoreTest.java) For the “ScoreTest” class, add “@ExtendWith(MockitoExtension.class)” annotation. In the “ScoreTest” class, add a Mock property of “Calculator” with “@Mock” and a property injecting Mocks of “Score” with “InjectMocks” annotation and a method of “testAdd()” with “@Test” annotation. In the method, add a mocking condition using “when”. package org.example.test1; import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.InjectMocks; import org.mockito.junit.jupiter.MockitoExtension; import static org.mockito.Mockito.when; import static org.mockito.ArgumentMatchers.anyString; @ExtendWith(MockitoExtension.class) class ScoreTest { @Mock Calculator calc; @InjectMocks Score score; @Test public void testAdd() { when(calc.evaluate(anyString())).thenReturn(5); int sum = score.add("1+4", "1+2+2"); assertEquals(10, sum); } } 84
  85. Java Unit Test with Mock Exercise • Procedure of the

    Exercise Edit pom.xml Make the Score Java Class Make a JUnit Test Class for the Score Execute JUnit from Eclipse Execute JUnit from Maven 85
  86. Java Unit Test with Mock Exercise • Execute JUnit directly

    for the created Java Test source file  Right click on the project and select “Run As”  “JUnit Test”  Confirm that JUnit finished successfully showing “Green” flag. 86
  87. Java Unit Test with Mock Exercise • Procedure of the

    Exercise Edit pom.xml Make the Score Java Class Make a JUnit Test Class for the Score Execute JUnit from Eclipse Execute JUnit from Maven 87
  88. Java Unit Test with Mock Exercise • Execute JUnit through

    M2Eclipse™ for the created Java Test source file  Right click on the project and select “Run As”  “Maven build” Confirm that test completes successfully in “Console” 88
  89. Java CDI Integration Test Example • Check if the “add”

    method of “Score” class works correctly along with “Calculator” class @RequestScoped public class Calculator { public int evaluate(String expression) { int sum = 0; for (String summand: expression.split("\\+")) sum += Integer.valueOf(summand); return sum; } } Calculator.java @RequestScoped public class Score { @Inject private Calculator calc; public int add(String expA, String expB) { int sum = calc.evaluate(expA) + calc.evaluate(expB); return sum; } } Score.java Target Class Injected Class 89 Exercise: Let’s make a Java CDI Integration Test Application to test the “add()” method of the “Score” CDI class injecting the “Calculator” CDI class with the above information.
  90. Java CDI Integration Test Exercise • Procedure of the Exercise

    Edit pom.xml Edit the Score and Calculator Java Class Make a JUnit Test Class for the Score Execute JUnit from Eclipse Execute JUnit from Maven 90
  91. Java CDI Integration Test Exercise • Modify the Maven Object

    Model file (pom.xml) Add “weld-junit5” and “weld-se-core” as dependency. <dependencies> : <dependency> <groupId>org.jboss.weld</groupId> <artifactId>weld-junit5</artifactId> <version>2.0.1.Final</version> <scope>test</scope> </dependency> <dependency> <groupId>org.jboss.weld.se</groupId> <artifactId>weld-se-core</artifactId> <version>3.1.5.Final</version> </dependency> : </dependencies> 91
  92. Java CDI Integration Test Exercise • Procedure of the Exercise

    Edit pom.xml Edit the Score and Calculator Java Class Make a JUnit Test Class for the Score Execute JUnit from Eclipse Execute JUnit from Maven 92
  93. Java CDI Integration Test Exercise • Modify the Java source

    file (Score.java)  In the “Score” class, add an annotation of “@RequestScoped” to Score Class definition and add an annotation of “@Inject” for the “Calculator” property for DI. package org.example.test1; import javax.inject.Inject; import javax.enterprise.context.RequestScoped; @RequestScoped public class Score { @Inject private Calculator calc; public int add(String expA, String expB) { int sum = calc.evaluate(expA) + calc.evaluate(expB); return sum; } } 93
  94. Java CDI Integration Test Exercise • Modify the Java source

    file (Calculator.java)  In the “Calculator” class, add an annotation of “@RequestScoped” to Calculator Class definition. package org.example.test1; import javax.enterprise.context.RequestScoped; @RequestScoped public class Calculator { public int evaluate(String expression) { int sum = 0; for (String summand: expression.split("\\+")) sum += Integer.valueOf(summand); return sum; } } 94
  95. Java CDI Integration Test Exercise • Procedure of the Exercise

    Edit pom.xml Edit the Score and Calculator Java Class Make a JUnit Test Class for the Score Execute JUnit from Eclipse Execute JUnit from Maven 95
  96. Java CDI Integration Test Exercise • Create a Test Class

    file for the created Java source file named “ScoreCDITest.java”  Right click on the package of “org.example.test1” under “src/test/java” and select “New”  “Other…”.  Select “Java”  “JUnit”  “JUnit Test Case” and click “Next >” button 96
  97. Java CDI Integration Test Exercise • Create a Test Class

    file for the created Java source file named “ScoreCDITest.java”  Fill “ScoreCDITest” in the Test Class Name field and click “Finish” button. 97
  98. Java CDI Integration Test Exercise • Modify the Java Test

    source file (ScoreCDITest.java) For the “ScoreCDITest” class, add “@EnableWeld”annotation. In the “ScoreCDITest” class, setup Weld with “@WeldSetup” for “Score” and “Caluculator” CDIs and add a property injecting “Score” CDI with “@Inject” annotation and a method of “testAdd()” with “@Test” annotation. package org.example.test1; import javax.inject.Inject; import javax.enterprise.context.RequestScoped; import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; import org.jboss.weld.junit5.EnableWeld; import org.jboss.weld.junit5.WeldSetup; import org.jboss.weld.junit5.WeldInitiator; @EnableWeld class ScoreCDITest { @WeldSetup public WeldInitiator weld = WeldInitiator.from(Score.class, Calculator.class).activate(RequestScoped.class, RequestScoped.class).build(); @Inject Score score; @Test public void testAdd() { int sum = score.add("1+4", "1+2+2"); assertEquals(10, sum); } } 98
  99. Java CDI Integration Test Exercise • Procedure of the Exercise

    Edit pom.xml Edit the Score and Calculator Java Class Make a JUnit Test Class for the Score Execute JUnit from Eclipse Execute JUnit from Maven 99
  100. Java CDI Integration Test Exercise • Execute JUnit directly for

    the created Java Test source file  Right click on the project and select “Run As”  “2 JUnit Test”  Confirm that JUnit finished successfully showing “Green” flag. 100
  101. Java CDI Integration Test Exercise • Procedure of the Exercise

    Edit pom.xml Edit the Score and Calculator Java Class Make a JUnit Test Class for the Score Execute JUnit from Eclipse Execute JUnit from Maven 101
  102. Java CDI Integration Test Exercise • Execute JUnit through M2Eclipse™

    for the created Java Test source file  Right click on the project and select “Run As”  “Maven build”  Confirm that test completes successfully in “Console” 102
  103. Java Web System Test Example • Check if a JSF

    menu works correctly binding the Score CDI component. @RequestScoped public class Calculator { public int evaluate(String expression) { int sum = 0; for (String summand: expression.split("\\+")) sum += Integer.valueOf(summand); return sum; } } Calculator.java @ReuqestScoped @Named public class Score { @Inject private Calculator calc; private String expA, expB, expSum; public void add() { int sum = calc.evaluate(expA) + calc.evaluate(expB); expSum = new Integer(sum).toString(); } } Score.java CDI Bean for JSF A: (Id: expA) B: (Id: expB) = (Id: expSum) + Calculate Accessors are required Web menu using JSF (Id: calculate) Bind Target Web Menu 103 Exercise: Let’s make a Java Web System Test Application to test a Web menu built with JSF Facelet which binds the “Score” CDI component.
  104. Java Web System Test Exercise • Procedure of the Exercise

    Make a Project and edit pom.xml Copy Score and Calculator Java Class and edit Score Make a web interface and JUnit Test Class for it Execute JUnit from Maven 104
  105. Java Unit Test Exercise • Create a new Eclipse™ Project

    named “test2” (1)  Right click in Project Explorer  “New”  “Project…”  Select “Maven”  “Maven Project” and click “Next >” button. 105
  106. Java Unit Test Exercise • Create a new Eclipse™ Project

    named “test2” (2)  Confirm “Use default Workspace location” is selected and click “Next >” button.  From “Select an Archetype” dialog menu, enter “myfaces-archetype-codi-jsf20” in Filter field and select “org.apache.myfaces.buildtools myfaces-archetype-codi-jsf20 1.0.4” and click “Next >” button. 106
  107. Java Unit Test Exercise • Create a new Eclipse™ Project

    named “test2” (3)  From “New Maven project” dialog menu, Enter a Group Id of “org.example” and a Artifact Id of “test2” and a Version of “0.0.1” and click “Finish” button. 107
  108. Java Web System Test Exercise • Modify the Maven Object

    Model file (pom.xml) (1)  Replace all parameters to access Payara Server which accommodates the target war file. <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> <servlet.port>8080</servlet.port> <payara.adminPort>4848</payara.adminPort> <payara.username>admin</payara.username> <payara.password>xxxxxxxx</payara.password> <payara.hostname>localhost</payara.hostname> <payara.domainName>domain1</payara.domainName> <payara.home>C:\payara5</payara.home> <payara.domainDir>${payara.home}/glassfish/domains</payara.domainDir> </properties> 108
  109. Java Web System Test Exercise • Modify the Maven Object

    Model file (pom.xml) (2)  Replace the build element to execute system test during “integration-test” phase. <build> <defaultGoal>package</defaultGoal> <finalName>${project.artifactId}</finalName> <plugins> <plugin> <artifactId>maven-surefire-plugin</artifactId> <version>2.22.2</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-failsafe-plugin</artifactId> <version>2.22.2</version> <executions> <execution> <id>perform-it</id> <goals> <goal>integration-test</goal> </goals> <configuration> <systemPropertyVariables> <servlet.host>${payara.hostname}</servlet.host> <servlet.port>${servlet.port}</servlet.port> <servlet.context>${project.artifactId}</servlet.context> </systemPropertyVariables> </configuration> </execution> </executions> </plugin> </plugins> </build> 109
  110. Java Web System Test Exercise • Modify the Maven Object

    Model file (3) (pom.xml)  Replace all dependencies. <dependencies> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-api</artifactId> <version>5.7.0</version> <scope>test</scope> </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-engine</artifactId> <version>5.7.0</version> <scope>test</scope> </dependency> <dependency> <groupId>org.hamcrest</groupId> <artifactId>hamcrest-core</artifactId> <version>2.2</version> <scope>test</scope> </dependency> <dependency> <groupId>javax</groupId> <artifactId>javaee-api</artifactId> <version>8.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>io.github.bonigarcia</groupId> <artifactId>selenium-jupiter</artifactId> <version>3.3.5</version> <scope>test</scope> </dependency> </dependencies> 110
  111. Java Web System Test Exercise • Modify the Maven Object

    Model file (pom.xml) (4)  Replace all profiles to start, stop Payara Server and deploy and undeploy war file to it. Profile description part will be provided by teacher 111
  112. Java Web System Test Exercise • Procedure of the Exercise

    Make a Project and edit pom.xml Copy Score and Calculator Java Class and edit Score Make a web interface and JUnit Test Class for it Execute JUnit from Maven 112
  113. Java Web System Test Exercise • Copy the Java source

    files (Score.java and Calculator.java)  Copy “Score.java” and “Calculator.java” from “test1” project and paste to “test2” project.  Delete “GreetingService.java” and “HelloWorldController.java”.  Update the Apache Maven™ Configuration of the “test2” project. (Hint: Right click on “test2” project and select “Maven” and click “Update project …”.) Delete Copy & Paste 113 Update Maven
  114. Java Web System Test Exercise • Modify the Java source

    file (Score.java) to be accessed from JSF Facelet menus  For the “Score” class, add an annotation of “@Named”.  Add menu field parameters and their accessors and change add() method to use the parameters. package org.example.test1; import javax.inject.Inject; import javax.inject.Named; import javax.enterprise.context.RequestScoped; @Named @RequestScoped public class Score { @Inject private Calculator calc; private String expA, expB, expSum; public String add() { int sum = calc.evaluate(expA) + calc.evaluate(expB); expSum = Integer.toString(sum); return "helloWorld"; } public String getExpA() { return expA;} public void setExpA(String expA) { this.expA = expA;} public String getExpB() { return expB;} public void setExpB(String expB) { this.expB = expB;} public String getExpSum() { return expSum;} public void setExpSum(String expSum) { this.expSum = expSum;} } 114
  115. Java Web System Test Exercise • Procedure of the Exercise

    Make a Project and edit pom.xml Copy Score and Calculator Java Class and edit Score Make a web interface and JUnit Test Class for it Execute JUnit from Maven 115
  116. Java Web System Test Exercise • Create Test folder 

    Right click on “test2” project and select “New”  “Source Folder”.  Fill in “src/test/java” for the “Folder name” field and click “Finish” button. (Hint: If you failed the above operation, create “src/test” folder manually and try again.) 116
  117. Java Web System Test Exercise • Create a Test Class

    file for the created Java source file named “ScoreIT.java” (1)  Right click on the created folder of “src/test/java” and select “New”  “Other…”.  Select “Java”  “JUnit”  “JUnit Test Case” and click “Next >” button. 117
  118. Java Web System Test Exercise • Create a Test Class

    file for the created Java source file named “ScoreIT.java” (2)  Fill “org.example.test2” in the “Package” field and “ScoreIT” in the “Name” field and click “Finish” button. 118
  119. Java Web System Test Exercise • Modify the Java Test

    source file (ScoreIT.java) For the “ScoreCDITest” class, add “@ExtendWith(SeleniumExtension.class)”annotation. In the “ScoreTest” class, add a method of “testAdd(ChromeDriver driver)” with “@Test” annotation. @ ExtendWith(SeleniumExtension.class) public class ScoreIT { @Test public void testAdd(ChromeDriver driver) throws InterruptedException{ String hostname = System.getProperty("servlet.host"); String port = System.getProperty("servlet.port"); String context = System.getProperty("servlet.context"); driver.get("http://" + hostname + ":" + port + "/" + context + "/"); WebElement element = driver.findElement(By.id("expA")); element.sendKeys("1+2+3"); element = driver.findElement(By.id("expB")); element.sendKeys("5+7+9"); element = driver.findElement(By.id("calculate")); element.click(); Thread.sleep(5000); element = driver.findElement(By.id("expSum")); assertEquals("27", element.getText()); }} package org.example.test2; import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.By; import io.github.bonigarcia.seljup.SeleniumExtension; 119
  120. Java Web System Test Exercise • Modify the Java Test

    source file (ScoreIT.java) (Optional) In the “ScoreTest” class, add a method of “setup()” with “@BeforeAll” annotation to force to specify a Chrom Driver version and to use Cache in the repository. @ ExtendWith(SeleniumExtension.class) public class ScoreIT { @BeforeAll static void setup() { // Specify a version of ChromeDriver WebDriverManager.chromedriver().version("84.0.4147.30"); // Force to use the local repository for the specific ChromeDriver // This prevents from accessing Internet. WebDriverManager.chromedriver().forceCache(); } : @Test public void testAdd(ChromeDriver driver) throws InterruptedException{ : } } package org.example.test2; import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.extension.ExtendWith; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.By; import io.github.bonigarcia.seljup.SeleniumExtension; import io.github.bonigarcia.wdm.WebDriverManager; 120
  121. Java Web System Test Exercise • Modify the Web XML

    file (web.xml)  Open “Deployed Resources”  “webapp”  “WEB-INF”  “web.xml”  Delete “Listener” part in the “web.xml”. Delete 121
  122. Java Web System Test Exercise • Modify the JSF Facelet

    file (helloWorld.xhtml)  Open “Deployed Resources”  “webapp”  “helloWorld.xhtml”  Change the form part of the Facelet file : <h:form id="mainForm" prependId="false"> <h:panelGrid columns="7"> <h:outputLabel for="expA" value="A:"/> <h:inputText id="expA" value="#{score.expA}" required="true"/> <h:outputText value="+"/> <h:outputLabel for="expB" value="B:"/> <h:inputText id="expB" value="#{score.expB}" required="true"/> <h:outputText value="="/> <h:outputText id="expSum" value="#{score.expSum}" /> <h:messages showDetail="true" showSummary="false"/> </h:panelGrid> <h:commandButton id="calculate" value="Calculate" action="#{score.add}"/> </h:form> : 122
  123. Java Web System Test Exercise • Procedure of the Exercise

    Make a Project and edit pom.xml Copy Score and Calculator Java Class and edit Score Make a web interface and JUnit Test Class for it Execute JUnit from Maven 123
  124. Java Web System Exercise • Execute JUnit through M2Eclipse™ for

    the created Java Test source file (Remote Profile)  Start-up Payara Server.  Right click on the project and select “Run As”  “Maven build…”  Put “test2 – post-integration-test (Remote)” in “Name” field and “post-integration-test” in “Goals” field and click “Run” button.  Confirm that test completes successfully in “Console” 124
  125. Java Web System Exercise • Execute JUnit through M2Eclipse™ for

    the created Java Test source file (Local Profile)  Edit C:\payara5\glassfish\domains\password.properties to change current admin password.  Shutdown Payara Server, if it’s working. Right click on the project and select “Run As”  “5 Maven build…”.  Put “test2 – post-integration-test (Local)” in “Name” field and “post-integration-test” in “Goals” field and “payara5x-local” in “Profile” field and click “Run” button.  Confirm that test completes successfully in “Console”. 125
  126. Exercise 126

  127. Java Unit Test Exercise • Check if the “dateToString” method

    of “DateUtility” class works correctly public class DateUtility { public String dateToString(LocalDateTime dateTime) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); String formattedString = dateTime.format(formatter); return formattedString; } } DateUtility.java Target Class 127
  128. Java Unit Test with Mock Exercise • Check if the

    “printToday” method of “DateForm” class works correctly by mocking “DateUtility” class public class DateUtility { public String dateToString(LocalDateTime dateTime) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); String formattedString = dateTime.format(formatter); return formattedString; } } DateUtility.java public class DateForm { private DateUtility du; public String printToday() { LocalDateTime now = LocalDateTime.now(); String dateString = du.dateToString(now); return dateString; } } DateForm.java Target Class Mocked Class ZonedDateTime zonedDateTimeNow = ZonedDateTime.now(ZoneId.of("UTC")); 128
  129. Java CDI Integration Test Exercise • Check if the “printToday”

    method of “DateForm” CDI class works correctly along with “DateUtility” CDI class @RequestScoped public class DateUtility { public String dateToString(LocalDateTime dateTime) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy"); String formattedString = dateTime.format(formatter); return formattedString; } } DateUtility.java @RequestScoped public class DateForm { @Inject private DateUtility du; public String printToday() { LocalDateTime now = LocalDateTime.now(); String dateString = du.dateToString(now); return dateString; } } DateForm.java Target Class Injected Class 129