TestNG – Test Results

TestNG – Test Results ”; Previous Next Reporting is the most important part of any test execution, as it helps the user understand the result of the test execution, point of failure, and the reasons for failure. Logging, on the other hand, is important to keep an eye on the execution flow or for debugging in case of any failures. TestNG, by default, generates a different type of report for its test execution. This includes an HTML and an XML report output. TestNG also allows its users to write their own reporter and use it with TestNG. There is also an option to write your own loggers, which are notified at runtime by TestNG. There are two ways to generate a report with TestNG − Listeners − For implementing a listener class, the class has to implement the org.testng.ITestListener interface. These classes are notified at runtime by TestNG when the test starts, finishes, fails, skips, or passes. Reporters − For implementing a reporting class, the class has to implement an org.testng.IReporter interface. These classes are called when the whole suite run ends. The object containing the information of the whole test run is passed to this class when called. In this chapter, we will have four different examples to demonstrate four different cases of reporting and logging − Sr.No. Case & Example 1 Custom Logging This example illustrates how to write your own logger. 2 Custom Reporter This example illustrates how to write your own reporter. 3 HTML and XML report This example illustrates the default HTML and XML report generated by TestNG. 4 JUnit Reports This example illustrates how to generate JUnit reports from TestNG reports. Print Page Previous Next Advertisements ”;

TestNG – Annotation Transformers

TestNG – Basic Annotations – Transformers ”; Previous Next In some scenarios you might want to execute TestNG tests based on some condition or criteria that is evaluated dynamically while test execution is in progress.Such as : Enable or disable a test Add data provider at run time In order to achieve this, you need to use an Annotation Transformer. An Annotation Transformer is a class that implements the following interface: public interface IAnnotationTransformer { /** * This method will be invoked by TestNG to give you a chance * to modify a TestNG annotation read from your test classes. * You can change the values you need by calling any of the * setters on the ITest interface. * * Note that only one of the three parameters testClass, * testConstructor and testMethod will be non-null. * * @param annotation The annotation that was read from your * test class. * @param testClass If the annotation was found on a class, this * parameter represents this class (null otherwise). * @param testConstructor If the annotation was found on a constructor, * this parameter represents this constructor (null otherwise). * @param testMethod If the annotation was found on a method, * this parameter represents this method (null otherwise). */ public void transform(ITest annotation, Class testClass, Constructor testConstructor, Method testMethod); } You can specify this class either on the command line or with ant as shown below: java org.testng.TestNG -listener TestTransformer testng.xml or programmatically as shown below: TestNG test = new TestNG(); test.setAnnotationTransformer(new TestTransformer()); // … This interface IAnnotationTransformer modifies the default TestNG tests behavior at run time. Using this listener, we can modify values of all attributes defined in @Test annotation by calling their setters. Create a Class Let”s see the usage of annotation transformer in below example. Let us skip tests that are tagged to a specified group without changing TestNG suite every time. Create a java class to be tested, say, ListenerTest.java in /work/testng/src. import org.testng.annotations.Test; public class ListenerTest { @Test(groups={“betaTest”,”aplhaTest”}) public void test1() { System.out.println(“I am test1”); } @Test(groups={“aplhaTest”}) public void test2() { System.out.println(“I am test2″); } } Create Tansformer class Case Class Create a java test class, say, TestTransformer.java(that implements IAnnotationTransformer) in /work/testng/src. Override method transform(). Add an Annotation @Test to methods test1() and test2() and group them. Add logic to skip tests with group name betaTest. Following are the TestTransformer.java contents. import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.util.Arrays; import java.util.List; import org.testng.IAnnotationTransformer; import org.testng.annotations.ITestAnnotation; public class TestTransformer implements IAnnotationTransformer{ @Override public void transform(ITestAnnotation annotation, Class testClass, Constructor testConstructor, Method testMethod) { List groupNames = Arrays.asList(annotation.getGroups()); System.out.println(groupNames.toString()); //Value ”betaTest” can be read from many places like properties file, run time parameter etc… //For Simplicity, group is hardcoded in this program String groupNameToSkip = “betaTest”; if(groupNames.contains(groupNameToSkip)){ System.out.println(“found group name”); annotation.setEnabled(false); } } } Create testng.xml Next, let”s create testng.xml file in /work/testng/src, to execute test case(s). <suite name=”Suite” parallel=”classes” thread-count=”2″> <listeners> <listener class-name=”TestTransformer”></listener> </listeners> <test name=”Test”> <classes> <class name=”ListenerTest”/> </classes> </test> </suite> Compile the test case using javac. /work/testng/src$ javac TestTransformer.java ListenerTest.java Now, run the testng.xml, which will run the test case defined in <test> tag. As you can see the tests grouped under name betaTest are skipped. /work/testng/src$ java org.testng.TestNG testng.xml Verify the output. [aplhaTest] [betaTest, aplhaTest] found group name I am test2 =============================================== Suite Total tests run: 1, Passes: 1, Failures: 0, Skips: 0 =============================================== Print Page Previous Next Advertisements ”;

TestNG – Exception Test

TestNG – Exception Test ”; Previous Next TestNG provides an option of tracing the exception handling of code. You can test whether a code throws a desired exception or not. Here the expectedExceptions parameter is used along with the @Test annotation. Now, let”s see @Test(expectedExceptions) in action. Create a Class Create a java class to be tested, say, MessageUtil.java in /work/testng/src. Add an error condition inside the printMessage() method. /* * This class prints the given message on console. */ public class MessageUtil { private String message; //Constructor //@param message to be printed public MessageUtil(String message) { this.message = message; } // prints the message public void printMessage() { System.out.println(message); int a =0; int b = 1/a; } // add “Hi!” to the message public String salutationMessage() { message = “Hi!” + message; System.out.println(message); return message; } } Create Test Case Class Create a java test class, say, ExpectedExceptionTest.java in /work/testng/src. Add an expected exception ArithmeticException to the testPrintMessage() test case. Following are the contents of ExpectedExceptionTest.java. import org.testng.Assert; import org.testng.annotations.Test; public class ExpectedExceptionTest { String message = “Manisha”; MessageUtil messageUtil = new MessageUtil(message); @Test(expectedExceptions = ArithmeticException.class) public void testPrintMessage() { System.out.println(“Inside testPrintMessage()”); messageUtil.printMessage(); } @Test public void testSalutationMessage() { System.out.println(“Inside testSalutationMessage()”); message = “Hi!” + “Manisha”; Assert.assertEquals(message,messageUtil.salutationMessage()); } } Create Test Runner Create testng.xml in /work/testng/src to execute test case(s). <?xml version = “1.0” encoding = “UTF-8”?> <!DOCTYPE suite SYSTEM “http://testng.org/testng-1.0.dtd” > <suite name = “Suite1”> <test name = “test1”> <classes> <class name = “ExpectedExceptionTest” /> </classes> </test> </suite> Compile the MessageUtil, Test case classes using javac. /work/testng/src$ javac MessageUtil.java TestJunit.java Now, run the Test Runner, which will run test cases defined in the provided Test Case class. /work/testng/src$ java org.testng.TestNG testng.xml Verify the output. testPrintMessage() test case will be passed. Inside testPrintMessage() Manisha Inside testSalutationMessage() Hi!Manisha =============================================== Suite1 Total tests run: 2, Failures: 0, Skips: 0 =============================================== Print Page Previous Next Advertisements ”;

TestNG – Plug with Eclipse

TestNG – Plug with Eclipse ”; Previous Next To set up TestNG with Eclipse, follow the steps given below − Step 1: Download TestNG Archive Download the latest version of TestNG jar file from http://www.testng.org OS Archive name Windows testng-7.4.jar Linux testng-7.4.jar Mac testng-7.4.jar We assume you have copied the above JAR file in /work/testng folder. Step 2: Set Eclipse environment Open eclipse → right click on the project and go to property → Build Path → Configure Build Path and add the testng-7.4.jar in the libraries using Add External Jar button. We assume that your Eclipse has inbuilt TestNG plug-in; if it is not available, then please get the latest version using the update site. In your Eclipse IDE, select Help / Eclipse Marketplace. Search for Testng. You will get the TestNG in the list. Click on Install as shown below: Now, your Eclipse is ready for the development of TestNG test cases. Step 3: Verify TestNG Installation in Eclipse Create a project TestNGProject in Eclipse at any location. Create a class MessageUtil to test in the project. /* * This class prints the given message on console. */ public class MessageUtil { private String message; //Constructor //@param message to be printed public MessageUtil(String message) { this.message = message; } // prints the message public String printMessage() { System.out.println(message); return message; } } Create a test class TestNGExample in the project. import org.testng.Assert; import org.testng.annotations.Test; public class TestNGExample { String message = “Hello World”; MessageUtil messageUtil = new MessageUtil(message); @Test public void testPrintMessage() { Assert.assertEquals(message,messageUtil.printMessage()); } } The project structure should be as follows − Finally, verify the output of the program by right-clicking on the program and running as TestNG. Verify the result. Print Page Previous Next Advertisements ”;

Spring MVC – Hello World Example

Spring MVC – Hello World Example ”; Previous Next The following example shows how to write a simple web based Hello World application using the Spring MVC Framework. To start with, let us have a working Eclipse IDE in place and follow the subsequent steps to develop a Dynamic Web Application using the Spring Web Framework. Step Description 1 Create a Dynamic Web Project with a name HelloWeb and create a package com.tutorialspoint under the src folder in the created project. 2 Drag and drop the following Spring and other libraries into the folder WebContent/WEB-INF/lib.. 3 Create a Java class HelloController under the com.tutorialspoint package. 4 Create Spring configuration files web.xml and HelloWeb-servlet.xml under the WebContent/WEB-INF folder. 5 Create a sub-folder with a name jsp under the WebContent/WEB-INFfolder. Create a view file hello.jsp under this sub-folder. 6 The final step is to create the content of the source and configuration files and export the application as explained below. HelloController.java package com.tutorialspoint; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.ui.ModelMap; @Controller @RequestMapping(“/hello”) public class HelloController{ @RequestMapping(method = RequestMethod.GET) public String printHello(ModelMap model) { model.addAttribute(“message”, “Hello Spring MVC Framework!”); return “hello”; } } web.xml <web-app id = “WebApp_ID” version = “2.4” xmlns = “http://java.sun.com/xml/ns/j2ee” xmlns:xsi = “http://www.w3.org/2001/XMLSchema-instance” xsi:schemaLocation = “http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd”> <display-name>Spring MVC Application</display-name> <servlet> <servlet-name>HelloWeb</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>HelloWeb</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app> HelloWeb-servlet.xml <beans xmlns = “http://www.springframework.org/schema/beans” xmlns:context = “http://www.springframework.org/schema/context” xmlns:xsi = “http://www.w3.org/2001/XMLSchema-instance” xsi:schemaLocation = ” http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd”> <context:component-scan base-package = “com.tutorialspoint” /> <bean class = “org.springframework.web.servlet.view.InternalResourceViewResolver”> <property name = “prefix” value = “/WEB-INF/jsp/” /> <property name = “suffix” value = “.jsp” /> </bean> </beans> hello.jsp <%@ page contentType = “text/html; charset = UTF-8″ %> <html> <head> <title>Hello World</title> </head> <body> <h2>${message}</h2> </body> </html> Following is the list of Spring and other libraries to be included in the web application. We can just drag these files and drop them in – WebContent/WEB-INF/lib folder. servlet-api-x.y.z.jar commons-logging-x.y.z.jar spring-aop-x.y.z.jar spring-beans-x.y.z.jar spring-context-x.y.z.jar spring-core-x.y.z.jar spring-expression-x.y.z.jar spring-webmvc-x.y.z.jar spring-web-x.y.z.jar Once you are done with creating source and configuration files, export your application. Right click on your application, use Export → WAR File option and save your HelloWeb.war file in Tomcat”s webapps folder. Now start your Tomcat server and make sure you are able to access other webpages from webapps folder using a standard browser. Now, try to access the URL − http://localhost:8080/HelloWeb/hello. If everything is fine with the Spring Web Application, we will see the following screen. You should note that in the given URL, HelloWeb is the application name and hello is the virtual subfolder, which we have mentioned in our controller using @RequestMapping(“/hello”). You can use direct root while mapping your URL using @RequestMapping(“/”), in this case you can access the same page using short URL http://localhost:8080/HelloWeb/, but it is advised to have different functionalities under different folders. Print Page Previous Next Advertisements ”;

Spring ORM – Update Project

Spring ORM – Update Project ”; Previous Next Let”s add the following classes in the project in the relevant packages. Employee class to be persisted in database. Employee.java package com.tutorialspoint.jpa.entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = “Employees”) public class Employee { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; @Column(name = “NAME”) private String name; @Column(name = “SALARY”) private double salary; @Column(name = “DESIGNATION”) private String designation; public Employee( ) { } public Employee(String name, double salary, String designation) { this.name = name; this.salary = salary; this.designation = designation; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getSalary() { return salary; } public void setSalary(double salary) { this.salary = salary; } public String getDesignation() { return designation; } public void setDesignation(String designation) { this.designation = designation; } } Employee DAO class to do operations on database. EmployeeDao.java package com.tutorialspoint.jpa.dao; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Root; import org.springframework.stereotype.Repository; import com.tutorialspoint.jpa.entity.Employee; @Repository public class EmployeeDao { @PersistenceContext private EntityManager em; public void add(Employee employee) { em.persist(employee); } public List<Employee> listEmployees() { CriteriaQuery<Employee> criteriaQuery = em.getCriteriaBuilder().createQuery(Employee.class); @SuppressWarnings(“unused”) Root<Employee> root = criteriaQuery.from(Employee.class); return em.createQuery(criteriaQuery).getResultList(); } } Employee Service class to use Employee DAO class. EmployeeService.java package com.tutorialspoint.jpa.service; import java.util.List; import javax.transaction.Transactional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.tutorialspoint.jpa.dao.EmployeeDao; import com.tutorialspoint.jpa.entity.Employee; @Service public class EmployeeService { @Autowired private EmployeeDao employeeDao; @Transactional public void add(Employee employee) { employeeDao.add(employee); } @Transactional() public List<Employee> listEmployees() { return employeeDao.listEmployees(); } } Application Configuration to be used by Spring framework. AppConfig.java package com.tutorialspoint.jpa; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.ComponentScans; import org.springframework.context.annotation.Configuration; import org.springframework.orm.jpa.JpaTransactionManager; import org.springframework.orm.jpa.LocalEntityManagerFactoryBean; import org.springframework.transaction.annotation.EnableTransactionManagement; @Configuration @EnableTransactionManagement @ComponentScans(value = { @ComponentScan(“com.tutorialspoint.jpa.dao”), @ComponentScan(“com.tutorialspoint.jpa.service”) }) public class AppConfig { @Bean public LocalEntityManagerFactoryBean geEntityManagerFactoryBean() { LocalEntityManagerFactoryBean factoryBean = new LocalEntityManagerFactoryBean(); factoryBean.setPersistenceUnitName(“Hibernate_JPA”); return factoryBean; } @Bean public JpaTransactionManager geJpaTransactionManager() { JpaTransactionManager transactionManager = new JpaTransactionManager(); transactionManager.setEntityManagerFactory(geEntityManagerFactoryBean().getObject()); return transactionManager; } } Main Application to run and test the functionalities. MainApp.java package com.tutorialspoint.jpa; import java.sql.SQLException; import java.util.List; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import com.tutorialspoint.jpa.entity.Employee; import com.tutorialspoint.jpa.service.EmployeeService; public class MainApp { public static void main(String[] args) throws SQLException { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class); EmployeeService employeeService = context.getBean(EmployeeService.class); employeeService.add(new Employee(“Julie”, 10000, “Technical Manager”)); employeeService.add(new Employee(“Robert”, 20000, “Senior Manager”)); employeeService.add(new Employee(“Anil”, 5000, “Software Engineer”)); // Get Persons List<Employee> employees = employeeService.listEmployees(); for (Employee employee : employees) { System.out.println(“Id : “+employee.getId()); System.out.println(“Name : “+employee.getName()); System.out.println(“Salary = “+employee.getSalary()); System.out.println(“Designation = “+employee.getDesignation()); System.out.println(); } context.close(); } } Print Page Previous Next Advertisements ”;

Spring MVC – Static Pages

Spring MVC – Static Pages Example ”; Previous Next The following example shows how to write a simple web based application using Spring MVC Framework, which can access static pages along with dynamic pages with the help of a <mvc:resources> tag. To begin with, let us have a working Eclipse IDE in place and adhere to the following steps to develop a Dynamic Form based Web Application using the Spring Web Framework. Step Description 1 Create a project with a name HelloWeb under a package com.tutorialspoint as explained in the Spring MVC – Hello World chapter. 2 Create a Java class WebController under the com.tutorialspoint package. 3 Create a static file final.htm under jsp sub-folder. 4 Update the Spring configuration file HelloWeb-servlet.xml under the WebContent/WEB-INF folder as shown below. 5 The final step is to create the content of the source and configuration files and export the application, which is explained below. WebController.java package com.tutorialspoint; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @Controller public class WebController { @RequestMapping(value = “/index”, method = RequestMethod.GET) public String index() { return “index”; } @RequestMapping(value = “/staticPage”, method = RequestMethod.GET) public String redirect() { return “redirect:/pages/final.htm”; } } HelloWeb-servlet.xml <?xml version = “1.0” encoding = “UTF-8”?> <beans xmlns = “http://www.springframework.org/schema/beans” xmlns:xsi = ” http://www.w3.org/2001/XMLSchema-instance” xmlns:context = “http://www.springframework.org/schema/context” xmlns:mvc = “http://www.springframework.org/schema/mvc” xsi:schemaLocation = “http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd”> <context:component-scan base-package = “com.tutorialspoint” /> <bean id = “viewResolver” class = “org.springframework.web.servlet.view.InternalResourceViewResolver”> <property name = “prefix” value = “/WEB-INF/jsp/” /> <property name = “suffix” value = “.jsp” /> </bean> <mvc:resources mapping = “/pages/**” location = “/WEB-INF/pages/” /> <mvc:annotation-driven/> </beans> Here, the <mvc:resources…./> tag is being used to map static pages. The mapping attribute must be an Ant pattern that specifies the URL pattern of an http requests. The location attribute must specify one or more valid resource directory locations having static pages including images, stylesheets, JavaScript, and other static content. Multiple resource locations may be specified using a comma-separated list of values. Following is the content of Spring view file WEB-INF/jsp/index.jsp. This will be a landing page; this page will send a request to access the staticPage service method, which will redirect this request to a static page available in WEB-INF/pages folder. index.jsp <%@taglib uri = “http://www.springframework.org/tags/form” prefix = “form”%> <html> <head> <title>Spring Landing Page</title> </head> <body> <h2>Spring Landing Pag</h2> <p>Click below button to get a simple HTML page</p> <form:form method = “GET” action = “/HelloWeb/staticPage”> <table> <tr> <td> <input type = “submit” value = “Get HTML Page”/> </td> </tr> </table> </form:form> </body> </html> final.htm <html> <head> <title>Spring Static Page</title> </head> <body> <h2>A simple HTML page</h2> </body> </html> Once you are done with creating source and configuration files, export your application. Right click on your application, use Export → WAR File option and save your HelloWeb.war file in Tomcat”s webapps folder. Now, start your Tomcat server and make sure you are able to access other webpages from webapps folder using a standard browser. Now try to access the URL – http://localhost:8080/HelloWeb/index. If everything is fine with the Spring Web Application, we will see the following screen. Click on “Get HTML Page” button to access a static page mentioned in the staticPage service method. If everything is fine with your Spring Web Application, we will see the following screen. Print Page Previous Next Advertisements ”;

Spring Boot – Google Cloud Platform

Spring Boot – Google Cloud Platform ”; Previous Next Google Cloud Platform provides a cloud computing services that run the Spring Boot application in the cloud environment. In this chapter, we are going to see how to deploy the Spring Boot application in GCP app engine platform. First, download the Gradle build Spring Boot application from Spring Initializer page www.start.spring.io. Observe the following screenshot. Now, in build.gradle file, add the Google Cloud appengine plugin and appengine classpath dependency. The code for build.gradle file is given below − buildscript { ext { springBootVersion = ”1.5.9.RELEASE” } repositories { mavenCentral() } dependencies { classpath(“org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}”) classpath ”com.google.cloud.tools:appengine-gradle-plugin:1.3.3” } } apply plugin: ”java” apply plugin: ”eclipse” apply plugin: ”org.springframework.boot” apply plugin: ”com.google.cloud.tools.appengine” group = ”com.tutorialspoint” version = ”0.0.1-SNAPSHOT” sourceCompatibility = 1.8 repositories { mavenCentral() } dependencies { compile(”org.springframework.boot:spring-boot-starter-web”) testCompile(”org.springframework.boot:spring-boot-starter-test”) } Now, write a simple HTTP Endpoint and it returns the String success as shown − package com.tutorialspoint.appenginedemo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @SpringBootApplication @RestController public class AppengineDemoApplication { public static void main(String[] args) { SpringApplication.run(AppengineDemoApplication.class, args); } @RequestMapping(value = “/”) public String success() { return “APP Engine deployment success”; } } Next, add the app.yml file under src/main/appengine directory as shown − runtime: java env: flex handlers: – url: /.* script: this field is required, but ignored Now, go to the Google Cloud console and click the Activate Google cloud shell at the top of the page. Now, move your source files and Gradle file into home directory of your google cloud machine by using google cloud shell. Now, execute the command gradle appengineDeploy and it will deploy your application into the Google Cloud appengine. Note − GCP should be billing enabled and before deploying your application into appengine, you should create appengine platform in GCP. It will take few minutes to deploy your application into GCP appengine platform. After build successful you can see the Service URL in console window. Now, hit the service URL and see the output. Google Cloud SQL To connect the Google Cloud SQL into your Spring Boot application, you should add the following properties into your application.properties file. JDBC URL Format jdbc:mysql://google/<DATABASE-NAME>?cloudSqlInstance = <GOOGLE_CLOUD_SQL_INSTANCE_NAME> &socketFactory = com.google.cloud.sql.mysql.SocketFactory&user = <USERNAME>&password = <PASSWORD> Note − The Spring Boot application and Google Cloud SQL should be in same GCP project. The application.properties file is given below. spring.dbProductService.driverClassName = com.mysql.jdbc.Driver spring.dbProductService.url = jdbc:mysql://google/PRODUCTSERVICE?cloudSqlInstance = springboot-gcp-cloudsql:asia-northeast1:springboot-gcp-cloudsql-instance&socketFactory = com.google.cloud.sql.mysql.SocketFactory&user = root&password = rootspring.dbProductService.username = root spring.dbProductService.password = root spring.dbProductService.testOnBorrow = true spring.dbProductService.testWhileIdle = true spring.dbProductService.timeBetweenEvictionRunsMillis = 60000 spring.dbProductService.minEvictableIdleTimeMillis = 30000 spring.dbProductService.validationQuery = SELECT 1 spring.dbProductService.max-active = 15 spring.dbProductService.max-idle = 10 spring.dbProductService.max-wait = 8000 YAML file users can add the below properties to your application.yml file. spring: datasource: driverClassName: com.mysql.jdbc.Driver url: “jdbc:mysql://google/PRODUCTSERVICE?cloudSqlInstance=springboot-gcp-cloudsql:asia-northeast1:springboot-gcp-cloudsql-instance&socketFactory=com.google.cloud.sql.mysql.SocketFactory&user=root&password=root” password: “root” username: “root” testOnBorrow: true testWhileIdle: true validationQuery: SELECT 1 max-active: 15 max-idle: 10 max-wait: 8000 Print Page Previous Next Advertisements ”;

Spring Boot – Batch Service

Spring Boot – Batch Service ”; Previous Next You can create an executable JAR file, and run the Spring Boot application by using the Maven or Gradle commands as shown below − For Maven, you can use the command given below − mvn clean install After “BUILD SUCCESS”, you can find the JAR file under the target directory. For Gradle, you can use the command as shown − gradle clean build After “BUILD SUCCESSFUL”, you can find the JAR file under the build/libs directory. Run the JAR file by using the command given here − java –jar <JARFILE> Now, the application has started on the Tomcat port 8080 as shown. Now, hit the URL http://localhost:8080/ in your web browser and connect the web socket and send the greeting and receive the message. Batch Service is a process to execute more than one command in a single task. In this chapter, you are going to learn how to create batch service in a Spring Boot application. Let us consider an example where we are going to save the CSV file content into HSQLDB. To create a Batch Service program, we need to add the Spring Boot Starter Batch dependency and HSQLDB dependency in our build configuration file. Maven users can add the following dependencies in pom.xml file. <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-batch</artifactId> </dependency> <dependency> <groupId>org.hsqldb</groupId> <artifactId>hsqldb</artifactId> </dependency> Gradle users can add the following dependencies in build.gradle file. compile(“org.springframework.boot:spring-boot-starter-batch”) compile(“org.hsqldb:hsqldb”) Now, add the simple CSV data file under classpath resources – src/main/resources and name the file as file.csv as shown − William,John Mike, Sebastian Lawarance, Lime Next, write a SQL script for HSQLDB – under the classpath resource directory – request_fail_hystrix_timeout DROP TABLE USERS IF EXISTS; CREATE TABLE USERS ( user_id BIGINT IDENTITY NOT NULL PRIMARY KEY, first_name VARCHAR(20), last_name VARCHAR(20) ); Create a POJO class for USERS model as shown − package com.tutorialspoint.batchservicedemo; public class User { private String lastName; private String firstName; public User() { } public User(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } @Override public String toString() { return “firstName: ” + firstName + “, lastName: ” + lastName; } } Now, create an intermediate processor to do the operations after the reading the data from the CSV file and before writing the data into SQL. package com.tutorialspoint.batchservicedemo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.batch.item.ItemProcessor; public class UserItemProcessor implements ItemProcessor<User, User> { private static final Logger log = LoggerFactory.getLogger(UserItemProcessor.class); @Override public User process(final User user) throws Exception { final String firstName = user.getFirstName().toUpperCase(); final String lastName = user.getLastName().toUpperCase(); final User transformedPerson = new User(firstName, lastName); log.info(“Converting (” + user + “) into (” + transformedPerson + “)”); return transformedPerson; } } Let us create a Batch configuration file, to read the data from CSV and write into the SQL file as shown below. We need to add the @EnableBatchProcessing annotation in the configuration class file. The @EnableBatchProcessing annotation is used to enable the batch operations for your Spring Boot application. package com.tutorialspoint.batchservicedemo; import javax.sql.DataSource; import org.springframework.batch.core.Job; import org.springframework.batch.core.Step; import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing; import org.springframework.batch.core.configuration.annotation.JobBuilderFactory; import org.springframework.batch.core.configuration.annotation.StepBuilderFactory; import org.springframework.batch.core.launch.support.RunIdIncrementer; import org.springframework.batch.item.database.BeanPropertyItemSqlParameterSourceProvider; import org.springframework.batch.item.database.JdbcBatchItemWriter; import org.springframework.batch.item.file.FlatFileItemReader; import org.springframework.batch.item.file.mapping.BeanWrapperFieldSetMapper; import org.springframework.batch.item.file.mapping.DefaultLineMapper; import org.springframework.batch.item.file.transform.DelimitedLineTokenizer; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.ClassPathResource; @Configuration @EnableBatchProcessing public class BatchConfiguration { @Autowired public JobBuilderFactory jobBuilderFactory; @Autowired public StepBuilderFactory stepBuilderFactory; @Autowired public DataSource dataSource; @Bean public FlatFileItemReader<User> reader() { FlatFileItemReader<User> reader = new FlatFileItemReader<User>(); reader.setResource(new ClassPathResource(“file.csv”)); reader.setLineMapper(new DefaultLineMapper<User>() { { setLineTokenizer(new DelimitedLineTokenizer() { { setNames(new String[] { “firstName”, “lastName” }); } }); setFieldSetMapper(new BeanWrapperFieldSetMapper<User>() { { setTargetType(User.class); } }); } }); return reader; } @Bean public UserItemProcessor processor() { return new UserItemProcessor(); } @Bean public JdbcBatchItemWriter<User> writer() { JdbcBatchItemWriter<User> writer = new JdbcBatchItemWriter<User>(); writer.setItemSqlParameterSourceProvider(new BeanPropertyItemSqlParameterSourceProvider<User>()); writer.setSql(“INSERT INTO USERS (first_name, last_name) VALUES (:firstName, :lastName)”); writer.setDataSource(dataSource); return writer; } @Bean public Job importUserJob(JobCompletionNotificationListener listener) { return jobBuilderFactory.get(“importUserJob”).incrementer( new RunIdIncrementer()).listener(listener).flow(step1()).end().build(); } @Bean public Step step1() { return stepBuilderFactory.get(“step1”).<User, User>chunk(10).reader(reader()).processor(processor()).writer(writer()).build(); } } The reader() method is used to read the data from the CSV file and writer() method is used to write a data into the SQL. Next, we will have to write a Job Completion Notification Listener class – used to notify after the Job completion. package com.tutorialspoint.batchservicedemo; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.listener.JobExecutionListenerSupport; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import org.springframework.stereotype.Component; @Component public class JobCompletionNotificationListener extends JobExecutionListenerSupport { private static final Logger log = LoggerFactory.getLogger(JobCompletionNotificationListener.class); private final JdbcTemplate jdbcTemplate; @Autowired public JobCompletionNotificationListener(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } @Override public void afterJob(JobExecution jobExecution) { if (jobExecution.getStatus() == BatchStatus.COMPLETED) { log.info(“!!! JOB FINISHED !! It”s time to verify the results!!”); List<User> results = jdbcTemplate.query( “SELECT first_name, last_name FROM USERS”, new RowMapper<User>() { @Override public User mapRow(ResultSet rs, int row) throws SQLException { return new User(rs.getString(1), rs.getString(2)); } }); for (User person : results) { log.info(“Found <” + person + “> in the database.”); } } } } Now, create an executable JAR file, and run the Spring Boot application by using the following Maven or Gradle commands. For Maven, use the command as shown − mvn clean install After “BUILD SUCCESS”, you can find the JAR file under the target directory. For Gradle, you can use the command as shown − gradle clean build After “BUILD SUCCESSFUL”, you can find the JAR file under the build/libs directory. Run the JAR file by using the command given here − java –jar <JARFILE> You can see the output in console window as shown − Print Page Previous Next Advertisements ”;

Spring Boot – Unit Test Cases

Spring Boot – Unit Test Cases ”; Previous Next Unit Testing is a one of the testing done by the developers to make sure individual unit or component functionalities are working fine. In this tutorial, we are going to see how to write a unit test case by using Mockito and Web Controller. Mockito For injecting Mockito Mocks into Spring Beans, we need to add the Mockito-core dependency in our build configuration file. Maven users can add the following dependency in your pom.xml file. <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-core</artifactId> <version>2.13.0</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> Gradle users can add the following dependency in the build.gradle file. compile group: ”org.mockito”, name: ”mockito-core”, version: ”2.13.0” testCompile(”org.springframework.boot:spring-boot-starter-test”) The code to write a Service class which contains a method that returns the String value is given here. package com.tutorialspoint.mockitodemo; import org.springframework.stereotype.Service; @Service public class ProductService { public String getProductName() { return “Honey”; } } Now, inject the ProductService class into another Service class file as shown. package com.tutorialspoint.mockitodemo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class OrderService { @Autowired ProductService productService; public OrderService(ProductService productService) { this.productService = productService; } public String getProductName() { return productService.getProductName(); } } The main Spring Boot application class file is given below − package com.tutorialspoint.mockitodemo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class MockitoDemoApplication { public static void main(String[] args) { SpringApplication.run(MockitoDemoApplication.class, args); } } Then, configure the Application context for the tests. The @Profile(“test”) annotation is used to configure the class when the Test cases are running. package com.tutorialspoint.mockitodemo; import org.mockito.Mockito; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.context.annotation.Profile; @Profile(“test”) @Configuration public class ProductServiceTestConfiguration { @Bean @Primary public ProductService productService() { return Mockito.mock(ProductService.class); } } Now, you can write a Unit Test case for Order Service under the src/test/resources package. package com.tutorialspoint.mockitodemo; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @SpringBootTest @ActiveProfiles(“test”) @RunWith(SpringJUnit4ClassRunner.class) public class MockitoDemoApplicationTests { @Autowired private OrderService orderService; @Autowired private ProductService productService; @Test public void whenUserIdIsProvided_thenRetrievedNameIsCorrect() { Mockito.when(productService.getProductName()).thenReturn(“Mock Product Name”); String testName = orderService.getProductName(); Assert.assertEquals(“Mock Product Name”, testName); } } The complete code for build configuration file is given below. Maven – pom.xml <?xml version = “1.0” encoding = “UTF-8”?> <project xmlns = “http://maven.apache.org/POM/4.0.0” xmlns:xsi = “http://www.w3.org/2001/XMLSchema-instance” xsi:schemaLocation = “http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd”> <modelVersion>4.0.0</modelVersion> <groupId>com.tutorialspoint</groupId> <artifactId>mockito-demo</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>mockito-demo</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.9.RELEASE</version> <relativePath /> <!– lookup parent from repository –> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-core</artifactId> <version>2.13.0</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> Gradle – build.gradle buildscript { ext { springBootVersion = ”1.5.9.RELEASE” } repositories { mavenCentral() } dependencies { classpath(“org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}”) } } apply plugin: ”java” apply plugin: ”eclipse” apply plugin: ”org.springframework.boot” group = ”com.tutorialspoint” version = ”0.0.1-SNAPSHOT” sourceCompatibility = 1.8 repositories { mavenCentral() } dependencies { compile(”org.springframework.boot:spring-boot-starter”) compile group: ”org.mockito”, name: ”mockito-core”, version: ”2.13.0” testCompile(”org.springframework.boot:spring-boot-starter-test”) } You can create an executable JAR file, and run the Spring Boot application by using the following Maven or Gradle1 commands. For Maven, you can use the command as shown − mvn clean install You can see the test results in console window. For Gradle, you can use the command as shown − gradle clean build You can see the rest results in console window. Print Page Previous Next Advertisements ”;