{"id":86381,"date":"2020-03-17T15:00:19","date_gmt":"2020-03-17T13:00:19","guid":{"rendered":"http:\/\/examples.javacodegeeks.com\/?p=86381"},"modified":"2021-05-25T16:59:58","modified_gmt":"2021-05-25T13:59:58","slug":"java-unit-testing-tutorial","status":"publish","type":"post","link":"https:\/\/examples.javacodegeeks.com\/java-unit-testing-tutorial\/","title":{"rendered":"Java Unit Testing Tutorial"},"content":{"rendered":"<p>This is a tutorial for Java unit testing. In this tutorial, I will create a spring boot application which includes test cases written with Junit, Mockito, and Spring test. The overall unit tests cover 90 percent of the application.<\/p>\n<p>You can also check this tutorial in the following video:<\/p>\n<figure class=\"wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio\">\n<div class=\"wp-block-embed__wrapper\">\n<iframe title=\"Unit Testing Tutorial\" width=\"500\" height=\"281\" src=\"https:\/\/www.youtube.com\/embed\/C5xSa3TWBuA?feature=oembed\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share\" referrerpolicy=\"strict-origin-when-cross-origin\" allowfullscreen><\/iframe>\n<\/div><figcaption>Unit Testing Tutorial &#8211; video<\/figcaption><\/figure>\n<div class=\"toc\">\n<h3>Table Of Contents<\/h3>\n<dl>\n<dt><a href=\"#heading1\">1. Introduction<\/a><\/dt>\n<dt><a href=\"#heading2\">2. Unit Testing Frameworks<\/a><\/dt>\n<dt><a href=\"#heading3\">3. Technologies Used<\/a><\/dt>\n<dt><a href=\"#heading4\">4. Maven Project<\/a><\/dt>\n<dd>\n<dl>\n<dt><a href=\"#heading41\">4.1 Dependencies<\/a><\/dt>\n<dt><a href=\"#heading42\">4.2 Application Properties<\/a><\/dt>\n<dt><a href=\"#heading43\">4.3 Application<\/a><\/dt>\n<dt><a href=\"#heading44\">4.4 Person Entity<\/a><\/dt>\n<dt><a href=\"#heading45\">4.5 User Not Found Exception<\/a><\/dt>\n<dt><a href=\"#heading46\">4.6 Person Repository<\/a><\/dt>\n<dt><a href=\"#heading47\">4.7 User<\/a><\/dt>\n<dt><a href=\"#heading48\">4.8 UserService<\/a><\/dt>\n<dt><a href=\"#heading49\">4.9 TransformService<\/a><\/dt>\n<dt><a href=\"#heading410\">4.10 UserServiceImpl<\/a><\/dt>\n<\/dl>\n<\/dd>\n<dt><a href=\"#heading5\">5. JUnit Test<\/a><\/dt>\n<dd>\n<dl>\n<dt><a href=\"#heading51\">5.1 PersonTest<\/a><\/dt>\n<dt><a href=\"#heading52\">5.2 PersonRepositoryTest<\/a><\/dt>\n<dt><a href=\"#heading53\">5.3 TransformServiceTest<\/a><\/dt>\n<dt><a href=\"#heading54\">5.4 MockUserServiceImplTest<\/a><\/dt>\n<dt><a href=\"#heading55\">5.5 UserServiceImplTest<\/a><\/dt>\n<\/dl>\n<\/dd>\n<dt><a href=\"#heading6\">6. Changes<\/a><\/dt>\n<dt><a href=\"#heading7\">7. Summary<\/a><\/dt>\n<dt><a href=\"#heading8\">8. Download the Source Code<\/a><\/dt>\n<\/dl>\n<\/div>\n<h2 class=\"wp-block-heading\" id=\"h-1-introduction\"><a name=\"heading1\"><\/a>1. Introduction<\/h2>\n<p>This is a tutorial for Java unit testing. A unit is an individual part which can also become a component of a larger system. In Java world, a unit can be a method or a class. Unit testing is a level of software testing where methods and classes are tested so that every unit of the software works as designed.<\/p>\n<p>Unit testing is the foundation of the &#8220;<a rel=\"noreferrer noopener\" aria-label=\"Testing Pyramid (opens in a new tab)\" href=\"https:\/\/www.mountaingoatsoftware.com\/blog\/the-forgotten-layer-of-the-test-automation-pyramid\" target=\"_blank\">Testing Pyramid<\/a>&#8221; outlined by <a rel=\"noreferrer noopener\" aria-label=\"Mike Cohn (opens in a new tab)\" href=\"https:\/\/en.wikipedia.org\/wiki\/Mike_Cohn\" target=\"_blank\">Mike Cohn<\/a>. It should be automated and run whenever there is a code change. With that, development is faster with the following benefits:<\/p>\n<ul class=\"wp-block-list\">\n<li>Codes are more reliable when it has a good amount of code coverage.<\/li>\n<li>Codes are more reusable because it&#8217;s easy to reuse modular code.<\/li>\n<li>The cost of fixing a defect detected during unit testing is lesser comparing to when defects detected at higher levels. <\/li>\n<li>It increases confidence when changing code. Every change is tested so the unintended impact of changes is identified. <\/li>\n<\/ul>\n<h2 class=\"wp-block-heading\" id=\"h-2-unit-testing-frameworks\"><a name=\"heading2\"><\/a>2. Unit Testing Frameworks<\/h2>\n<p>There are lots of Java unit testing frameworks. In this example, I will demonstrate unit testing with the following frameworks:<\/p>\n<ul class=\"wp-block-list\">\n<li>Junit &#8211; A standard for Java unit testing which provides <code>@Test<\/code> annotation to specify tests and assertion methods: <code>assertEquals()<\/code>, <code>assertTrue()<\/code>, and <code>assertFalse()<\/code>. <\/li>\n<li>Mockito &#8211; a mocking framework which provides <code>@Mock<\/code> annotation to mock the dependency with mocking methods: <code>when<\/code>, <code>thenReturn<\/code>, <code>doNothing<\/code>, and <code>doThrow<\/code>.<\/li>\n<li>Spring Test and Spring Boot Test &#8211; a test library which tests spring boot application.<\/li>\n<\/ul>\n<p>I will create a spring boot application which contains test classes to test key methods.<\/p>\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large\"><img decoding=\"async\" width=\"798\" height=\"611\" src=\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2020\/03\/junit.jpg\" alt=\"Java Unit Testing Tutorial - Class Digram\" class=\"wp-image-86703\" srcset=\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2020\/03\/junit.jpg 798w, https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2020\/03\/junit-300x230.jpg 300w, https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2020\/03\/junit-768x588.jpg 768w\" sizes=\"(max-width: 798px) 100vw, 798px\" \/><figcaption>Figure 1 Class Digram<\/figcaption><\/figure>\n<\/div>\n<h2 class=\"wp-block-heading\" id=\"h-3-technologies-used\"><a name=\"heading3\"><\/a>3. Technologies Used<\/h2>\n<p>The example code in this article was built and run using:<\/p>\n<ul class=\"wp-block-list\">\n<li>Java 8<\/li>\n<li>Maven 3.3.9<\/li>\n<li>Eclipse Oxygen<\/li>\n<li>H2<\/li>\n<li>Spring boot (which includes Spring test, JUnit, and Mockito)<\/li>\n<\/ul>\n<h2 class=\"wp-block-heading\" id=\"h-4-maven-project\"><a name=\"heading4\"><\/a>4. Maven Project<\/h2>\n<h3 class=\"wp-block-heading\" id=\"h-4-1-dependencies\"><a name=\"heading41\"><\/a>4.1 Dependencies<\/h3>\n<p><strong>Pom.xml<\/strong> includes dependencies for this project.<\/p>\n<p><span style=\"text-decoration: underline\"><em>pom.xml<\/em><\/span>\n<\/p>\n<pre class=\"wp-block-preformatted brush:xml\">&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt;\n&lt;project xmlns=\"http:\/\/maven.apache.org\/POM\/4.0.0\" xmlns:xsi=\"http:\/\/www.w3.org\/2001\/XMLSchema-instance\"\n\txsi:schemaLocation=\"http:\/\/maven.apache.org\/POM\/4.0.0 http:\/\/maven.apache.org\/xsd\/maven-4.0.0.xsd\"&gt;\n\t&lt;modelVersion&gt;4.0.0&lt;\/modelVersion&gt;\n\n\t&lt;groupId&gt;jcg.zheng.demo&lt;\/groupId&gt;\n\t&lt;artifactId&gt;junit-demo&lt;\/artifactId&gt;\n\t&lt;version&gt;0.0.1-SNAPSHOT&lt;\/version&gt;\n\t&lt;packaging&gt;jar&lt;\/packaging&gt;\n\n\t&lt;name&gt;spring-boot-jersey-demo&lt;\/name&gt;\n\t&lt;description&gt;Demo project for Spring Boot&lt;\/description&gt;\n\n\t&lt;parent&gt;\n\t\t&lt;groupId&gt;org.springframework.boot&lt;\/groupId&gt;\n\t\t&lt;artifactId&gt;spring-boot-starter-parent&lt;\/artifactId&gt;\n\t\t&lt;version&gt;1.5.14.RELEASE&lt;\/version&gt;\n\t\t&lt;relativePath\/&gt; &lt;!-- lookup parent from repository --&gt;\n\t&lt;\/parent&gt;\n\n\t&lt;properties&gt;\n\t\t&lt;project.build.sourceEncoding&gt;UTF-8&lt;\/project.build.sourceEncoding&gt;\n\t\t&lt;project.reporting.outputEncoding&gt;UTF-8&lt;\/project.reporting.outputEncoding&gt;\n\t\t&lt;java.version&gt;1.8&lt;\/java.version&gt;\n\t&lt;\/properties&gt;\n\n\t&lt;dependencies&gt;\n\t\t&lt;dependency&gt;\n\t\t\t&lt;groupId&gt;org.springframework.boot&lt;\/groupId&gt;\n\t\t\t&lt;artifactId&gt;spring-boot-starter-data-jpa&lt;\/artifactId&gt;\n\t\t&lt;\/dependency&gt;\n\n\t\t&lt;dependency&gt;\n\t\t\t&lt;groupId&gt;com.h2database&lt;\/groupId&gt;\n\t\t\t&lt;artifactId&gt;h2&lt;\/artifactId&gt;\n\t\t\t&lt;scope&gt;runtime&lt;\/scope&gt;\n\t\t&lt;\/dependency&gt;\n\t\t&lt;dependency&gt;\n\t\t\t&lt;groupId&gt;org.springframework.boot&lt;\/groupId&gt;\n\t\t\t&lt;artifactId&gt;spring-boot-starter-test&lt;\/artifactId&gt;\n\t\t\t&lt;scope&gt;test&lt;\/scope&gt;\n\t\t&lt;\/dependency&gt;\n\t&lt;\/dependencies&gt;\n\n\t&lt;build&gt;\n\t\t&lt;plugins&gt;\n\t\t\t&lt;plugin&gt;\n\t\t\t\t&lt;groupId&gt;org.springframework.boot&lt;\/groupId&gt;\n\t\t\t\t&lt;artifactId&gt;spring-boot-maven-plugin&lt;\/artifactId&gt;\n\t\t\t&lt;\/plugin&gt;\n\t\t&lt;\/plugins&gt;\n\t&lt;\/build&gt;\n\n\n&lt;\/project&gt;\n<\/pre>\n<h3 class=\"wp-block-heading\" id=\"h-4-2-application-properties\"><a name=\"heading42\"><\/a>4.2 Application Properties<\/h3>\n<p>In this step, I will create an <code>application.properties<\/code> to configure a H2 database and spring JPA hibernate configuration.<\/p>\n<p><span style=\"text-decoration: underline\"><em>application.properties<\/em><\/span>\n<\/p>\n<pre class=\"wp-block-preformatted brush:bash\">spring.datasource.url=jdbc:h2:file:~\/main-source;AUTO_SERVER=TRUE\nspring.datasource.username=sa\nspring.datasource.password=\nspring.datasource.driver-class-name=org.h2.Driver\n\nspring.jpa.hibernate.ddl-auto=create\nspring.jpa.generate-ddl=true\nspring.jpa.show-sql=true\n<\/pre>\n<h3 class=\"wp-block-heading\" id=\"h-4-3-application\"><a name=\"heading43\"><\/a>4.3 Application<\/h3>\n<p>In this step, I will create an <code>Application.java<\/code> class which annotates with <code>@SpringBootApplication<\/code>. It only has a main method to start the application.<\/p>\n<p><span style=\"text-decoration: underline\"><em>Application.java<\/em><\/span> <\/p>\n<pre class=\"wp-block-preformatted brush:java\">package jcg.zheng.demo;\n\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\n\n@SpringBootApplication\npublic class Application {\n\tpublic static void main(String[] args) {\n\t\tSpringApplication.run(Application.class, args);\n\t}\n}\n<\/pre>\n<h3 class=\"wp-block-heading\" id=\"h-4-4-person-entity\"><a name=\"heading44\"><\/a>4.4 Person Entity<\/h3>\n<p>In this step, I will create a <code>Person<\/code> class which represents an <a rel=\"noreferrer noopener\" aria-label=\"entity  (opens in a new tab)\" href=\"https:\/\/docs.oracle.com\/cd\/E19798-01\/821-1841\/bnbqb\/index.html\" target=\"_blank\">entity<\/a> class. It annotates with <code>@javax.persistence.Entity<\/code>, <code>@javax.persistence.Id<\/code>, <code>@javax.persistence.GeneratedValue<\/code>, etc.<\/p>\n<p><span style=\"text-decoration: underline\"><em>Person.java<\/em><\/span> <\/p>\n<pre class=\"wp-block-preformatted brush:java\">package jcg.zheng.demo.entity;\n\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\n\n@Entity\npublic class Person {\n\n\tprivate String companyName;\n\n\tprivate String fName;\n\tprivate String lName;\n\tprivate String mName;\n\t@Id\n\t@GeneratedValue(strategy = GenerationType.IDENTITY)\n\tprivate int personId;\n\n\tpublic String getCompanyName() {\n\t\treturn companyName;\n\t}\n\n\tpublic String getfName() {\n\t\treturn fName;\n\t}\n\n\tpublic String getlName() {\n\t\treturn lName;\n\t}\n\n\tpublic String getmName() {\n\t\treturn mName;\n\t}\n\n\tpublic int getPersonId() {\n\t\treturn personId;\n\t}\n\n\tpublic void setCompanyName(String companyName) {\n\t\tthis.companyName = companyName;\n\t}\n\n\tpublic void setfName(String fName) {\n\t\tthis.fName = fName;\n\t}\n\n\tpublic void setlName(String lName) {\n\t\tthis.lName = lName;\n\t}\n\n\tpublic void setmName(String mName) {\n\t\tthis.mName = mName;\n\t}\n\n\tpublic void setPersonId(int personId) {\n\t\tthis.personId = personId;\n\t}\n\n}\n<\/pre>\n<h3 class=\"wp-block-heading\" id=\"h-4-5-user-not-found-exception\"><a name=\"heading45\"><\/a>4.5 User Not Found Exception<\/h3>\n<p>In this step, I will create a <code>UserNotFoundException<\/code> which extends from <code>RuntimeException<\/code>.<\/p>\n<p><span style=\"text-decoration: underline\"><em>UserNotFoundException.java<\/em><\/span> <\/p>\n<pre class=\"wp-block-preformatted brush:java\">package jcg.zheng.demo.exception;\n\npublic class UserNotFoundException extends RuntimeException {\n\n\tprivate static final long serialVersionUID = 3873418545077760440L;\n\n\tprivate final Integer userId;\n\n\tpublic UserNotFoundException(String message, Integer userId) {\n\t\tsuper(message);\n\t\tthis.userId = userId;\n\t}\n\n\tpublic Integer getUserId() {\n\t\treturn userId;\n\t}\n}\n<\/pre>\n<h3 class=\"wp-block-heading\" id=\"h-4-6-person-repository\"><a name=\"heading46\"><\/a>4.6 Person Repository<\/h3>\n<p>In this step, I will create a <code>PersonRepository<\/code> interface which extends from <code>JpaRepository<\/code> and have one customized query &#8211; <code>findByCompany<\/code>.<\/p>\n<p><span style=\"text-decoration: underline\"><em>PersonRepository.java<\/em><\/span> <\/p>\n<pre class=\"wp-block-preformatted brush:java\">package jcg.zheng.demo.repository;\n\nimport java.util.List;\n\nimport org.springframework.data.jpa.repository.JpaRepository;\nimport org.springframework.data.jpa.repository.Query;\nimport org.springframework.data.repository.query.Param;\nimport org.springframework.stereotype.Repository;\n\nimport jcg.zheng.demo.entity.Person;\n\n@Repository\npublic interface PersonRepository extends JpaRepository&lt;Person, Integer&gt; {\n\n\t@Query(\"SELECT person from Person person WHERE person.companyName = :companyName\")\n\tList&lt;Person&gt; findByCompany(@Param(\"companyName\") String companyName);\n\n}\n<\/pre>\n<h3 class=\"wp-block-heading\" id=\"h-4-7-user\"><a name=\"heading47\"><\/a>4.7 User<\/h3>\n<p>In this step, I will create a <code>User<\/code> domain class which has several data members and overwrites the <code>equals<\/code> and <code>hashCode<\/code> methods.<div style=\"display:inline-block; margin: 15px 0;\"> <div id=\"adngin-JavaCodeGeeks_incontent_video-0\" style=\"display:inline-block;\"><\/div> <\/div><\/p>\n<p><span style=\"text-decoration: underline\"><em>User.java<\/em><\/span> <\/p>\n<pre class=\"wp-block-preformatted brush:java\">package jcg.zheng.demo.service;\n\npublic class User {\n\n\tprivate String companyName;\n\n\tprivate String firstName;\n\n\tprivate String lastName;\n\n\tprivate Integer userId;\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj)\n\t\t\treturn true;\n\t\tif (obj == null)\n\t\t\treturn false;\n\t\tif (getClass() != obj.getClass())\n\t\t\treturn false;\n\t\tUser other = (User) obj;\n\t\tif (userId == null) {\n\t\t\tif (other.userId != null)\n\t\t\t\treturn false;\n\t\t} else if (!userId.equals(other.userId))\n\t\t\treturn false;\n\t\treturn true;\n\t}\n\n\tpublic String getCompanyName() {\n\t\treturn companyName;\n\t}\n\n\tpublic String getFirstName() {\n\t\treturn firstName;\n\t}\n\n\tpublic String getLastName() {\n\t\treturn lastName;\n\t}\n\n\tpublic Integer getUserId() {\n\t\treturn userId;\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\tfinal int prime = 31;\n\t\tint result = 1;\n\t\tresult = prime * result + ((userId == null) ? 0 : userId.hashCode());\n\t\treturn result;\n\t}\n\n\tpublic void setCompanyName(String companyName) {\n\t\tthis.companyName = companyName;\n\t}\n\n\tpublic void setFirstName(String firstName) {\n\t\tthis.firstName = firstName;\n\t}\n\n\tpublic void setLastName(String lastName) {\n\t\tthis.lastName = lastName;\n\t}\n\n\tpublic void setUserId(Integer userId) {\n\t\tthis.userId = userId;\n\t}\n\n}\n<\/pre>\n<h3 class=\"wp-block-heading\" id=\"h-4-8-userservice\"><a name=\"heading48\"><\/a>4.8 UserService<\/h3>\n<p>In this step, I will create a <code>UserService<\/code> interface which has four public methods.<\/p>\n<p><span style=\"text-decoration: underline\"><em>UserService.java<\/em><\/span> <\/p>\n<pre class=\"wp-block-preformatted brush:java\">package jcg.zheng.demo.service;\n\nimport java.util.List;\n\npublic interface UserService {\n\n\tvoid deleteById(Integer personId);\n\n\tUser findById(Integer personId);\n\n\tUser save(User user);\n\n\tList searchByCompanyName(String companyName);\n\n}<\/pre>\n<h3 class=\"wp-block-heading\" id=\"h-4-9-transformservice\"><a name=\"heading49\"><\/a>4.9 TransformService<\/h3>\n<p>In this step, I will create a spring managed component &#8211; <code>TransformService<\/code> which transforms the <code>Person<\/code> entity to <code>User<\/code> domain and vice versa.<\/p>\n<p><span style=\"text-decoration: underline\"><em>UserServiceImpl.java<\/em><\/span> <\/p>\n<pre class=\"wp-block-preformatted brush:java\">package jcg.zheng.demo.service;\n\nimport org.springframework.stereotype.Component;\n\nimport jcg.zheng.demo.entity.Person;\n\n@Component\npublic class TransformService {\n\n\tpublic User toUserDomain(final Person person) {\n\t\tUser user = new User();\n\t\tuser.setCompanyName(person.getCompanyName());\n\t\tuser.setFirstName(person.getfName());\n\t\tuser.setLastName(person.getlName());\n\t\tuser.setUserId(person.getPersonId());\n\t\treturn user;\n\t}\n\n\tpublic Person toUserEntity(final User user) {\n\t\tPerson person = new Person();\n\t\tperson.setCompanyName(user.getCompanyName());\n\t\tperson.setfName(user.getFirstName());\n\t\tperson.setlName(user.getLastName());\n\t\tif (user.getUserId() != null) {\n\t\t\tperson.setPersonId(user.getUserId());\n\t\t}\n\t\treturn person;\n\t}\n}\n<\/pre>\n<h3 class=\"wp-block-heading\" id=\"h-4-10-userserviceimpl\"><a name=\"heading410\"><\/a>4.10 UserServiceImpl<\/h3>\n<p>In this step, I will create a spring managed component &#8211; <code>UserServiceImpl<\/code> which implements the <code>UserService<\/code> interface. It depends on the <code>PersonRepository<\/code> and <code>TransformServie<\/code>.<\/p>\n<p><span style=\"text-decoration: underline\"><em>UserServiceImpl.java<\/em><\/span> <\/p>\n<pre class=\"wp-block-preformatted brush:java\">package jcg.zheng.demo.service;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport javax.transaction.Transactional;\n\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Component;\n\nimport jcg.zheng.demo.entity.Person;\nimport jcg.zheng.demo.exception.UserNotFoundException;\nimport jcg.zheng.demo.repository.PersonRepository;\n\n@Component\n@Transactional\npublic class UserServiceImpl implements UserService {\n\n\t@Autowired\n\tprivate PersonRepository personDao;\n\n\t@Autowired\n\tprivate TransformService transformer;\n\n\t@Override\n\tpublic void deleteById(Integer personId) {\n\t\tpersonDao.delete(personId);\n\t}\n\n\t@Override\n\tpublic User findById(Integer personId) {\n\t\tPerson found = personDao.findOne(personId);\n\n\t\tif (found == null) {\n\t\t\tthrow new UserNotFoundException(\"not found user\", personId);\n\t\t}\n\t\treturn transformer.toUserDomain(found);\n\t}\n\n\t@Override\n\tpublic User save(User user) {\n\t\tPerson saved = personDao.save(transformer.toUserEntity(user));\n\t\treturn transformer.toUserDomain(saved);\n\t}\n\n\t@Override\n\tpublic List&lt;User&gt; searchByCompanyName(String companyName) {\n\t\tList&lt;Person&gt; persons = personDao.findByCompany(companyName);\n\t\tList&lt;User&gt; users = new ArrayList&lt;&gt;();\n\t\tfor (Person person : persons) {\n\t\t\tusers.add(transformer.toUserDomain(person));\n\t\t}\n\t\treturn users;\n\t}\n}\n<\/pre>\n<h2 class=\"wp-block-heading\" id=\"h-5-junit-test\"><a name=\"heading5\"><\/a>5. JUnit Test<\/h2>\n<p>In this section, I will create several test classes that utilize Junit, Mockito, and spring test frameworks. In this example, I will use the following annotations throughout the project.<\/p>\n<figure class=\"wp-block-table\">\n<table>\n<tbody>\n<tr>\n<td><strong>Framework<\/strong><\/td>\n<td><strong>Common Annotations<\/strong><\/td>\n<td><strong>Comments<\/strong><\/td>\n<\/tr>\n<tr>\n<td>JUnit<\/td>\n<td>@Test<\/td>\n<td>Mark it at a public void method to indicate it is a test case<\/td>\n<\/tr>\n<tr>\n<td>JUnit <\/td>\n<td>@Rule<\/td>\n<td>Mark it at a public variable to let JUnit run it as a test rule<\/td>\n<\/tr>\n<tr>\n<td>JUnit <\/td>\n<td>@Before<\/td>\n<td>Mark it at a public void method to let Junit execute it before any test case<\/td>\n<\/tr>\n<tr>\n<td>JUnit<\/td>\n<td>@RunWith<\/td>\n<td>Specify a test class with a non-default runner<\/td>\n<\/tr>\n<tr>\n<td>Spring Test<\/td>\n<td>@SpringBootTest<\/td>\n<td>Set up application context for the testing purpose<\/td>\n<\/tr>\n<tr>\n<td>Spring Test<\/td>\n<td>@DataJpaTest<\/td>\n<td>Set up context to test JpaRepository<\/td>\n<\/tr>\n<tr>\n<td>Mockito<\/td>\n<td>@Mock<\/td>\n<td>Create a mock object<\/td>\n<\/tr>\n<tr>\n<td>Mockito<\/td>\n<td>@InjectMocks<\/td>\n<td>Create an object and inject the marked dependencies<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/figure>\n<p>Each test case is structured with <strong>Given, When, Then<\/strong> sequences. It sets up the data, invokes the testing method, and verifies the output. This project has 90% code coverage with unit tests.<\/p>\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large\"><img decoding=\"async\" width=\"753\" height=\"308\" src=\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2020\/03\/junit-coverage.jpg\" alt=\"\" class=\"wp-image-86704\" srcset=\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2020\/03\/junit-coverage.jpg 753w, https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2020\/03\/junit-coverage-300x123.jpg 300w\" sizes=\"(max-width: 753px) 100vw, 753px\" \/><figcaption>Figure 2 Code Coverage<\/figcaption><\/figure>\n<\/div>\n<h3 class=\"wp-block-heading\" id=\"h-5-1-persontest\"><a name=\"heading51\"><\/a>5.1 PersonTest<\/h3>\n<p><code>Person<\/code> is an entity class which annotates with <code>@Entity<\/code> annotation. It must have a default constructor, so I will test its default constructor in the <code>PersonTest.java<\/code><\/p>\n<p><span style=\"text-decoration: underline\"><em>PersonTest.java<\/em><\/span> <\/p>\n<pre class=\"wp-block-preformatted brush:java\">package jcg.zheng.demo.entity;\n\nimport static org.junit.Assert.assertEquals;\n\nimport org.junit.Test;\n\npublic class PersonTest {\n\n\t@Test\n\tpublic void test_person_default_constructor() {\n\t\tPerson testClass = new Person();\n\t\t\n\t\ttestClass.setmName(\"Shan\");\n\t\tassertEquals(\"Shan\", testClass.getmName());\n\n\t\ttestClass.setfName(\"Mary\");\n\t\tassertEquals(\"Mary\", testClass.getfName());\n\n\t\ttestClass.setlName(\"Zheng\");\n\t\tassertEquals(\"Zheng\", testClass.getlName());\n\t}\n\n}\n<\/pre>\n<p>Execute it with maven command <code>mvn test -Dtest=PersonTest<\/code> and capture the output here.<\/p>\n<p><span style=\"text-decoration: underline\"><em>Output<\/em><\/span>\n<\/p>\n<pre class=\"wp-block-preformatted brush:bash\">Running jcg.zheng.demo.entity.PersonTest\nTests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.005 sec - in jcg.zheng.demo.entity.PersonTest\n\nResults :\n\nTests run: 1, Failures: 0, Errors: 0, Skipped: 0<\/pre>\n<h3 class=\"wp-block-heading\" id=\"h-5-2-personrepositorytest\"><a name=\"heading52\"><\/a>5.2 PersonRepositoryTest<\/h3>\n<p>In this step, I will use the <code>@DataJpaTest<\/code> provided by spring test framework to auto-wire the <code>TestEntityManager<\/code> and <code>PersonRepository<\/code> from the spring context. It has a <code>Timeout<\/code> rule to ensure every test must complete within 2 seconds. It has one <code>setup<\/code> and four test cases:<\/p>\n<ul class=\"wp-block-list\">\n<li><code>setup<\/code> &#8211; it verifies that the spring test framework provides the needed beans &#8211; <code>entityManger<\/code> and <code>personDao<\/code> and uses them to create two persons in database for other tests to use.<\/li>\n<li><code>findByCompany_return_emptylist_when_not_found<\/code> &#8211; it returns an empty list when there is no person matching the given company.<\/li>\n<li><code>findByCompany_return_person_when_found<\/code> &#8211; it finds a list of people which matches the given company.<\/li>\n<li><code>findOne_return_null_when_not_found<\/code> &#8211; it returns a null object when it doesn&#8217;t find a user based on the person id.<\/li>\n<li><code>findAll_return_list_when_found<\/code> &#8211; it returns all persons in the database as a list.<\/li>\n<\/ul>\n<p><span style=\"text-decoration: underline\"><em>PersonRepositoryTest.java<\/em><\/span> <\/p>\n<pre class=\"wp-block-preformatted brush:java\">package jcg.zheng.demo.repository;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertNotNull;\nimport static org.junit.Assert.assertNull;\nimport static org.junit.Assert.assertTrue;\n\nimport java.util.List;\n\nimport org.junit.Before;\nimport org.junit.Rule;\nimport org.junit.Test;\nimport org.junit.rules.Timeout;\nimport org.junit.runner.RunWith;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;\nimport org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager;\nimport org.springframework.test.context.junit4.SpringRunner;\n\nimport jcg.zheng.demo.entity.Person;\n\n@RunWith(SpringRunner.class)\n@DataJpaTest\npublic class PersonRepositoryTest {\n\n\t@Rule\n\tpublic Timeout appTimeout = Timeout.millis(2000);\n\n\t@Autowired\n\tprivate TestEntityManager entityManager;\n\t@Autowired\n\tprivate PersonRepository personDao;\n\n\t@Before\n\tpublic void setup() {\n\t\tassertNotNull(entityManager);\n\t\tassertNotNull(personDao);\n\n\t\t\/\/ prepare two persons\n\t\tPerson mary = new Person();\n\t\tmary.setfName(\"Mary\");\n\t\tmary.setCompanyName(\"Test\");\n\t\tentityManager.persist(mary);\n\n\t\tPerson alex = new Person();\n\t\talex.setfName(\"Alex\");\n\t\talex.setCompanyName(\"Alex company\");\n\t\tentityManager.persist(alex);\n\n\t}\n\n\t@Test\n\tpublic void findAll_return_list_when_found() {\n\t\tList&lt;Person&gt; found = personDao.findAll();\n\n\t\tassertNotNull(found);\n\t\tassertEquals(2, found.size());\n\t}\n\n\t@Test\n\tpublic void findByCompany_return_person_when_found() {\n\t\tList&lt;Person&gt; found = personDao.findByCompany(\"Test\");\n\n\t\tassertNotNull(found);\n\t\tassertEquals(\"Mary\", found.get(0).getfName());\n\t}\n\n\t@Test\n\tpublic void findByCompany_return_emptylist_when_not_found() {\n\t\tList&lt;Person&gt; found = personDao.findByCompany(\"Test-notExist\");\n\n\t\tassertNotNull(found);\n\t\tassertTrue(found.isEmpty());\n\n\t}\n\n\t@Test\n\tpublic void findOne_return_null_when_not_found() {\n\t\tPerson found = personDao.findOne(-9);\n\n\t\tassertNull(found);\n\t}\n\n}\n<\/pre>\n<p>Execute it with maven command <code>mvn test -Dtest=PersonRepositoryTest<\/code> and capture the output here.<\/p>\n<p><span style=\"text-decoration: underline\"><em>Output<\/em><\/span>\n<\/p>\n<pre class=\"wp-block-preformatted brush:bash\">Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 10.913 sec - in jcg.zheng.demo.repository.PersonRepositoryTest\n2020-03-14 16:11:17.596  INFO 140944 --- [       Thread-2] s.c.a.AnnotationConfigApplicationContext : Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@1ed6388a: startup date [Sat Mar 14 16:11:08 CDT 2020]; root of context hierarchy\n2020-03-14 16:11:17.603  INFO 140944 --- [       Thread-2] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'\n\nResults :\n\nTests run: 4, Failures: 0, Errors: 0, Skipped: 0<\/pre>\n<h3 class=\"wp-block-heading\" id=\"h-5-3-transformservicetest\"><a name=\"heading53\"><\/a>5.3 TransformServiceTest<\/h3>\n<p>Although <code>TransformService<\/code> is managed by spring, but it has no dependency to other services. We will test it with two simple Junit test methods:<\/p>\n<ul class=\"wp-block-list\">\n<li><code>test_toDomain<\/code> &#8211; it tests the <code>toUserDomain<\/code> method<\/li>\n<li><code>test_toEntity<\/code> &#8211; it tests the <code>toUserEntity<\/code> method<\/li>\n<\/ul>\n<p><span style=\"text-decoration: underline\"><em>TransformServiceTest.java<\/em><\/span> <\/p>\n<pre class=\"wp-block-preformatted brush:java\">package jcg.zheng.demo.service;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertNotNull;\n\nimport org.junit.Test;\n\nimport jcg.zheng.demo.entity.Person;\n\npublic class TransformServiceTest {\n\n\tprivate TransformService testClass = new TransformService() ;\n\n\t@Test\n\tpublic void test_toDomain() {\n\t\tPerson person = new Person();\n\t\tperson.setCompanyName(\"test company\");\n\t\tperson.setfName(\"Mary\");\n\t\tperson.setlName(\"Zheng\");\n\t\tperson.setmName(\"shan\");\n\t\tperson.setPersonId(1);\n\t\tUser user = testClass.toUserDomain(person);\n\n\t\tassertNotNull(user);\n\t\tassertEquals(\"test company\", user.getCompanyName());\n\t\tassertEquals(\"Mary\", user.getFirstName());\n\t\tassertEquals(\"Zheng\", user.getLastName());\n\t\tassertEquals(1, user.getUserId().intValue());\n\t}\n\n\t@Test\n\tpublic void test_toEntity() {\n\t\tUser user = new User();\n\n\t\tuser.setCompanyName(\"test company\");\n\t\tuser.setFirstName(\"Mary\");\n\t\tuser.setLastName(\"Zheng\");\n\t\tuser.setUserId(Integer.valueOf(1));\n\n\t\tPerson person = testClass.toUserEntity(user);\n\n\t\tassertNotNull(user);\n\t\tassertEquals(\"test company\", person.getCompanyName());\n\t\tassertEquals(\"Mary\", person.getfName());\n\t\tassertEquals(\"Zheng\", person.getlName());\n\t\tassertEquals(1, person.getPersonId());\n\t}\n\n}\n<\/pre>\n<p>Execute it with maven command <code>mvn test -Dtest=TransformServiceTest<\/code> and capture the output here.<\/p>\n<p><span style=\"text-decoration: underline\"><em>Output<\/em><\/span>\n<\/p>\n<pre class=\"wp-block-preformatted brush:bash\">Running jcg.zheng.demo.service.TransformServiceTest\nTests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.016 sec - in jcg.zheng.demo.service.TransformServiceTest\n\nResults :\n\nTests run: 2, Failures: 0, Errors: 0, Skipped: 0<\/pre>\n<h3 class=\"wp-block-heading\" id=\"h-5-4-mockuserserviceimpltest\"><a name=\"heading54\"><\/a>5.4 MockUserServiceImplTest<\/h3>\n<p><code>UserServiceImpl<\/code> class has two dependencies: <code>PersonRepository<\/code> to access database, <code>TransformService<\/code> to transform the <code>Person<\/code> entity to <code>User<\/code> domain object. In this step, I will use Mockito to mock these two dependencies and how these two dependencies behave when they are invoked inside the <code>UserServiceImpl<\/code> class.<\/p>\n<ul class=\"wp-block-list\">\n<li><code>@Mock<\/code> &#8211; mocks the dependency<\/li>\n<li><code>@InjectMocks<\/code> &#8211; mocks the testing class<\/li>\n<li><code>findById_found<\/code> &#8211; tests the <code>findById<\/code> method when the id is available in database by mocking the <code>personRepository.findOne<\/code> method to return a person object.<\/li>\n<li><code>findById_not_found<\/code> &#8211; tests the <code>findById<\/code> method when the id is not found in database by mocking the <code>personRepository.findOne<\/code> method to return a <code>null<\/code> object<\/li>\n<li>searchByCompanyName_found &#8211; tests searchByCompanyName method when a list of people are found in database by mocking <code>personRepository.findByCompany<\/code> to return a list of person objects<\/li>\n<li><code>searchByCompanyName_not_found<\/code> &#8211; tests <code>searchByCompanyName<\/code> method when a list of people are not found in database by mocking <code>personRepository.<\/code>findByCompany to return an empty list.<\/li>\n<li><code>deleteById_is_done_by_dao_delete<\/code> &#8211; tests <code>deleteById<\/code> by mocking a void method &#8211; <code>personRepository<\/code> .delete<\/li>\n<li><code>mock_db_exception<\/code> &#8211; tests the service will throw exception when database throws exception.<\/li>\n<\/ul>\n<p><span style=\"text-decoration: underline\"><em>MockUserServiceImplTest.java<\/em><\/span> <\/p>\n<pre class=\"wp-block-preformatted brush:java\">package jcg.zheng.demo.service;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertTrue;\nimport static org.mockito.Mockito.doNothing;\nimport static org.mockito.Mockito.doReturn;\nimport static org.mockito.Mockito.doThrow;\nimport static org.mockito.Mockito.times;\nimport static org.mockito.Mockito.verify;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.mockito.InjectMocks;\nimport org.mockito.Matchers;\nimport org.mockito.Mock;\nimport org.mockito.runners.MockitoJUnitRunner;\n\nimport jcg.zheng.demo.entity.Person;\nimport jcg.zheng.demo.exception.UserNotFoundException;\nimport jcg.zheng.demo.repository.PersonRepository;\n\n@RunWith(MockitoJUnitRunner.class)\npublic class MockUserServiceImplTest {\n\n\tprivate static final String MARY = \"Mary\";\n\tprivate static final String TEST_COMPANY = \"Test\";\n\tprivate Person person = new Person();\n\t@Mock\n\tprivate PersonRepository personDao;\n\n\t@InjectMocks\n\tprivate UserServiceImpl testClass;\n\n\t@Mock\n\tprivate TransformService transformer;\n\n\tprivate User user = new User();\n\n\t@Test\n\tpublic void findById_found() {\n\t\tdoReturn(person).when(personDao).findOne(Integer.valueOf(1));\n\t\tdoReturn(user).when(transformer).toUserDomain(person);\n\n\t\tUser user = testClass.findById(Integer.valueOf(1));\n\t\tassertEquals(MARY, user.getFirstName());\n\t}\n\n\t@Test(expected = UserNotFoundException.class)\n\tpublic void findById_not_found() {\n\t\tdoReturn(null).when(personDao).findOne(Integer.valueOf(1));\n\n\t\ttestClass.findById(Integer.valueOf(1));\n\t}\n\n\t@Test\n\tpublic void searchByCompanyName_found() {\n\t\tList&lt;Person&gt; persons = new ArrayList&lt;&gt;();\n\t\tpersons.add(person);\n\t\tdoReturn(persons).when(personDao).findByCompany(TEST_COMPANY);\n\t\tdoReturn(user).when(transformer).toUserDomain(person);\n\n\t\tList&lt;User&gt; users = testClass.searchByCompanyName(TEST_COMPANY);\n\t\tassertEquals(1, users.size());\n\t\tassertEquals(MARY, users.get(0).getFirstName());\n\t}\n\n\t@Test\n\tpublic void searchByCompanyName_not_found() {\n\t\tList&lt;Person&gt; persons = new ArrayList&lt;&gt;();\n\t\tdoReturn(persons).when(personDao).findByCompany(TEST_COMPANY);\n\t\tdoReturn(user).when(transformer).toUserDomain(person);\n\n\t\tList&lt;User&gt; users = testClass.searchByCompanyName(TEST_COMPANY);\n\t\tassertTrue(users.isEmpty());\n\t}\n\n\t@Test\n\tpublic void deleteById_is_done_by_dao_delete() {\n\t\tdoNothing().when(personDao).delete(Matchers.any(Integer.class));\n\n\t\ttestClass.deleteById(Integer.valueOf(1));\n\n\t\tverify(personDao, times(1)).delete(Integer.valueOf(1));\n\t\t;\n\t}\n\n\t@Test(expected = Exception.class)\n\tpublic void mock_db_exception() {\n\t\tdoThrow(new Exception(\"bad db\")).when(personDao).delete(Matchers.any(Integer.class));\n\t}\n\n\t@Before\n\tpublic void setup() {\n\t\tperson.setfName(MARY);\n\t\tuser.setFirstName(MARY);\n\t}\n}\n<\/pre>\n<p>Execute it with maven command <code>mvn test -Dtest=MockUserServiceImplTest<\/code> and capture the output here.<\/p>\n<p><span style=\"text-decoration: underline\"><em>Output<\/em><\/span>\n<\/p>\n<pre class=\"wp-block-preformatted brush:bash\">Running jcg.zheng.demo.service.MockUserServiceImplTest\nTests run: 6, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.425 sec - in jcg.zheng.demo.service.MockUserServiceImplTest\n\nResults :\n\nTests run: 6, Failures: 0, Errors: 0, Skipped: 0<\/pre>\n<h3 class=\"wp-block-heading\" id=\"h-5-5-userserviceimpltest\"><a name=\"heading55\"><\/a>5.5 UserServiceImplTest<\/h3>\n<p>Spring test frameworks provides <code>@SpringBootTest<\/code> which starts the spring context with all the needed objects. In this step, I will create a <code>UserServiceImplTest<\/code> class which auto-wires <code>UserService<\/code> with the following testing methods:<\/p>\n<ul class=\"wp-block-list\">\n<li><code>findById_throw_exception_when_not_found<\/code> &#8211; expects to throw <code>UserNotfoundException<\/code> when user is not in database.<\/li>\n<li><code>test_save_findById_searchByCompanyName<\/code> &#8211; tests the <code>searchByCompanyName<\/code> first, then it saves a person in database, then it finds the saved person, finally, it deletes it from database.<\/li>\n<li><code>searchByCompanyName_return_empty_when_not_found<\/code> &#8211; returns an empty list when there is no person matches the company name.<\/li>\n<\/ul>\n<p>Please note that these tests also test the <code>PersonRepository<\/code> and <code>TransformService<\/code>. It takes longer time ( 8.99 seconds) than the unit test &#8211; <code>MockUserServiceImpl<\/code> which takes 0.4 seconds.<\/p>\n<p><span style=\"text-decoration: underline\"><em>UserServiceImplTest.java<\/em><\/span> <\/p>\n<pre class=\"wp-block-preformatted brush:java\">package jcg.zheng.demo.service;\n\nimport static org.junit.Assert.assertNotNull;\nimport static org.junit.Assert.assertTrue;\n\nimport java.util.List;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.boot.test.context.SpringBootTest;\nimport org.springframework.test.context.junit4.SpringRunner;\n\nimport jcg.zheng.demo.exception.UserNotFoundException;\n\n@RunWith(SpringRunner.class)\n@SpringBootTest\npublic class UserServiceImplTest {\n\n\t@Autowired\n\tprivate UserService userService;\n\n\t@Test(expected = UserNotFoundException.class)\n\tpublic void findById_throw_exception_when_not_found() {\n\t\tuserService.findById(Integer.valueOf(-1));\n\t}\n\n\t@Test\n\tpublic void searchByCompanyName_return_empty_when_not_found() {\n\t\tList&lt;User&gt; found = userService.searchByCompanyName(\"Test\");\n\t\tassertTrue(found.isEmpty());\n\t}\n\n\t@Test\n\tpublic void test_save_findById_searchByCompanyName() {\n\t\tUser user = new User();\n\t\tuser.setFirstName(\"Mary\");\n\t\tuser.setLastName(\"Zheng\");\n\t\tuser.setCompanyName(\"Test\");\n\t\tuser = userService.save(user);\n\t\tassertNotNull(user.getUserId());\n\n\t\tUser foundUser = userService.findById(user.getUserId());\n\t\tassertTrue(foundUser.equals(user));\n\t\tuserService.deleteById(user.getUserId());\n\n\t\tList&lt;User&gt; found = userService.searchByCompanyName(\"Test\");\n\t\tassertTrue(found.isEmpty());\n\t}\n\n}\n<\/pre>\n<p>Execute it with maven command <code>mvn test -Dtest=UserServiceImplTest<\/code> and capture the output here.<\/p>\n<p><span style=\"text-decoration: underline\"><em>Output<\/em><\/span>\n<\/p>\n<pre class=\"wp-block-preformatted brush:bash\">Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 8.995 sec - in jcg.zheng.demo.service.UserServiceImplTest\n2020-03-14 16:27:28.967  INFO 140044 --- [       Thread-5] s.c.a.AnnotationConfigApplicationContext : Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@4a668b6e: startup date [Sat Mar 14 16:27:21 CDT 2020]; root of context hierarchy\n2020-03-14 16:27:28.975  INFO 140044 --- [       Thread-5] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'\n\nResults :\n\nTests run: 3, Failures: 0, Errors: 0, Skipped: 0<\/pre>\n<h2 class=\"wp-block-heading\" id=\"h-6-changes\"><a name=\"heading6\"><\/a>6. Changes <\/h2>\n<p>Imaging the application is in use for a while and business requires a change to use a default system user when the given user is not found in the database. <\/p>\n<p>I will update the <code>UserServiceImpl.java<\/code> class for this change. <\/p>\n<p><span style=\"text-decoration: underline\"><em>UserServiceImplTest.java<\/em><\/span> <\/p>\n<pre class=\"wp-block-preformatted brush:java\">package jcg.zheng.demo.service;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport javax.transaction.Transactional;\n\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Component;\n\nimport jcg.zheng.demo.entity.Person;\nimport jcg.zheng.demo.exception.UserNotFoundException;\nimport jcg.zheng.demo.repository.PersonRepository;\n\n@Component\n@Transactional\npublic class UserServiceImpl implements UserService {\n\n @Autowired\n private PersonRepository personDao;\n\n @Autowired\n private TransformService transformer;\n\n @Override\n public void deleteById(Integer personId) {\n personDao.delete(personId);\n }\n\n @Override\n public User findById(Integer personId) {\n Person found = personDao.findOne(personId);\n\n if (found == null) {\n Person defaultPerson = new Person();\n defaultPerson.setfName(\"default\");\n defaultPerson.setlName(\"System\");\n defaultPerson.setCompanyName(\"Default\");\n found = defaultPerson;\n }\n return transformer.toUserDomain(found);\n }\n\n @Override\n public User save(User user) {\n Person saved = personDao.save(transformer.toUserEntity(user));\n return transformer.toUserDomain(saved);\n }\n\n @Override\n public List&lt;User&gt; searchByCompanyName(String companyName) {\n List&lt;Person&gt; persons = personDao.findByCompany(companyName);\n List&lt;User&gt; users = new ArrayList&lt;&gt;();\n for (Person person : persons) {\n users.add(transformer.toUserDomain(person));\n }\n return users;\n }\n}\n<\/pre>\n<p>After this change, I will see the JUnit test failed at <code>findById_not_found<\/code> immediately.<\/p>\n<pre class=\"wp-block-preformatted brush:plain\">Failed tests:\n  MockUserServiceImplTest.findById_not_found Expected exception: jcg.zheng.demo.exception.UserNotFoundException\n\nTests run: 6, Failures: 1, Errors: 0, Skipped: 0<\/pre>\n<p>In this case, I will fix the test case &#8211; <code>findById_not_found<\/code> to not throw the <code>UserNotFoundException<\/code>.<\/p>\n<pre class=\"wp-block-preformatted brush:java\">\t@Test \n\tpublic void findById_not_found() {\n\t\tdoReturn(null).when(personDao).findOne( Matchers.any(Integer.class));\n\t\t \n\t\tdoReturn(user).when(transformer).toUserDomain(Matchers.any(Person.class));\n\t\t\n\t\tUser default_user = testClass.findById(Integer.valueOf(1));\n\t\tassertNotNull(default_user);\n\t\t \n\t}<\/pre>\n<h2 class=\"wp-block-heading\" id=\"h-7-unit-testing-tutorial-summary\"><a name=\"heading7\"><\/a>7. Unit Testing Tutorial &#8211; Summary<\/h2>\n<p>In this example, I demonstrated how to write a unit test in Junit, Mockito, and Spring test frameworks. As we have seen here, the Mockito test is faster than the spring Jpa test. Spring test is not truly unit testing as it relies on the spring context.<\/p>\n<p>There are other common testing frameworks which support unit testing:<\/p>\n<ul class=\"wp-block-list\">\n<li>TestNG &#8211; similar to Junit and enables customized tests which reads test data from a spreadsheet. <\/li>\n<li>EasyMock &#8211; similar to Mockito.<\/li>\n<li>PowerMock &#8211; can mock static methods, constructors, and private methods. <\/li>\n<\/ul>\n<h2 class=\"wp-block-heading\" id=\"h-8-download-the-source-code\"><a name=\"heading8\"><\/a>8. Download the Source Code<\/h2>\n<div class=\"download\"><strong>Download<\/strong><br \/>\nYou can download the full source code of this example here: <a href=\"http:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2020\/03\/junit-demo-1.zip\"><strong>Java Unit Testing Tutorial<\/strong><\/a><\/div>\n","protected":false},"excerpt":{"rendered":"<p>This is a tutorial for Java unit testing. In this tutorial, I will create a spring boot application which includes test cases written with Junit, Mockito, and Spring test. The overall unit tests cover 90 percent of the application. You can also check this tutorial in the following video: Unit Testing Tutorial &#8211; video Table &hellip;<\/p>\n","protected":false},"author":140,"featured_media":1204,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[5],"tags":[],"class_list":["post-86381","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-core-java"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v26.5 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Java Unit Testing Tutorial - Java Code Geeks<\/title>\n<meta name=\"description\" content=\"This is a tutorial for Java unit testing. In this tutorial, I will create a spring boot application which includes test cases written with Junit, Mockito,\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/examples.javacodegeeks.com\/java-unit-testing-tutorial\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Java Unit Testing Tutorial - Java Code Geeks\" \/>\n<meta property=\"og:description\" content=\"This is a tutorial for Java unit testing. In this tutorial, I will create a spring boot application which includes test cases written with Junit, Mockito,\" \/>\n<meta property=\"og:url\" content=\"https:\/\/examples.javacodegeeks.com\/java-unit-testing-tutorial\/\" \/>\n<meta property=\"og:site_name\" content=\"Examples Java Code Geeks\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/javacodegeeks\" \/>\n<meta property=\"article:published_time\" content=\"2020-03-17T13:00:19+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2021-05-25T13:59:58+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2012\/12\/java-logo.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"150\" \/>\n\t<meta property=\"og:image:height\" content=\"150\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"Mary Zheng\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@javacodegeeks\" \/>\n<meta name=\"twitter:site\" content=\"@javacodegeeks\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Mary Zheng\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"14 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/java-unit-testing-tutorial\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/java-unit-testing-tutorial\/\"},\"author\":{\"name\":\"Mary Zheng\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/#\/schema\/person\/8a2034fbabcb20a9396e9819261855ae\"},\"headline\":\"Java Unit Testing Tutorial\",\"datePublished\":\"2020-03-17T13:00:19+00:00\",\"dateModified\":\"2021-05-25T13:59:58+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/java-unit-testing-tutorial\/\"},\"wordCount\":1426,\"commentCount\":0,\"publisher\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/#organization\"},\"image\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/java-unit-testing-tutorial\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2012\/12\/java-logo.jpg\",\"articleSection\":[\"Core Java\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/examples.javacodegeeks.com\/java-unit-testing-tutorial\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/java-unit-testing-tutorial\/\",\"url\":\"https:\/\/examples.javacodegeeks.com\/java-unit-testing-tutorial\/\",\"name\":\"Java Unit Testing Tutorial - Java Code Geeks\",\"isPartOf\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/java-unit-testing-tutorial\/#primaryimage\"},\"image\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/java-unit-testing-tutorial\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2012\/12\/java-logo.jpg\",\"datePublished\":\"2020-03-17T13:00:19+00:00\",\"dateModified\":\"2021-05-25T13:59:58+00:00\",\"description\":\"This is a tutorial for Java unit testing. In this tutorial, I will create a spring boot application which includes test cases written with Junit, Mockito,\",\"breadcrumb\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/java-unit-testing-tutorial\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/examples.javacodegeeks.com\/java-unit-testing-tutorial\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/java-unit-testing-tutorial\/#primaryimage\",\"url\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2012\/12\/java-logo.jpg\",\"contentUrl\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2012\/12\/java-logo.jpg\",\"width\":150,\"height\":150,\"caption\":\"Bipartite Graph\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/java-unit-testing-tutorial\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/examples.javacodegeeks.com\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Java Development\",\"item\":\"https:\/\/examples.javacodegeeks.com\/category\/java-development\/\"},{\"@type\":\"ListItem\",\"position\":3,\"name\":\"Core Java\",\"item\":\"https:\/\/examples.javacodegeeks.com\/category\/java-development\/core-java\/\"},{\"@type\":\"ListItem\",\"position\":4,\"name\":\"Java Unit Testing Tutorial\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/#website\",\"url\":\"https:\/\/examples.javacodegeeks.com\/\",\"name\":\"Java Code Geeks\",\"description\":\"Java Examples and Code Snippets\",\"publisher\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/#organization\"},\"alternateName\":\"JCG\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/examples.javacodegeeks.com\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/#organization\",\"name\":\"Exelixis Media P.C.\",\"url\":\"https:\/\/examples.javacodegeeks.com\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2022\/06\/exelixis-logo.png\",\"contentUrl\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2022\/06\/exelixis-logo.png\",\"width\":864,\"height\":246,\"caption\":\"Exelixis Media P.C.\"},\"image\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/www.facebook.com\/javacodegeeks\",\"https:\/\/x.com\/javacodegeeks\"]},{\"@type\":\"Person\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/#\/schema\/person\/8a2034fbabcb20a9396e9819261855ae\",\"name\":\"Mary Zheng\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2017\/11\/Mary-Zheng_avatar_1510732235-96x96.jpg\",\"contentUrl\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2017\/11\/Mary-Zheng_avatar_1510732235-96x96.jpg\",\"caption\":\"Mary Zheng\"},\"description\":\"Mary has graduated from Mechanical Engineering department at ShangHai JiaoTong University. She also holds a Master degree in Computer Science from Webster University. During her studies she has been involved with a large number of projects ranging from programming and software engineering. She works as a senior Software Engineer in the telecommunications sector where she acts as a leader and works with others to design, implement, and monitor the software solution.\",\"url\":\"https:\/\/examples.javacodegeeks.com\/author\/mary-zheng\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Java Unit Testing Tutorial - Java Code Geeks","description":"This is a tutorial for Java unit testing. In this tutorial, I will create a spring boot application which includes test cases written with Junit, Mockito,","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/examples.javacodegeeks.com\/java-unit-testing-tutorial\/","og_locale":"en_US","og_type":"article","og_title":"Java Unit Testing Tutorial - Java Code Geeks","og_description":"This is a tutorial for Java unit testing. In this tutorial, I will create a spring boot application which includes test cases written with Junit, Mockito,","og_url":"https:\/\/examples.javacodegeeks.com\/java-unit-testing-tutorial\/","og_site_name":"Examples Java Code Geeks","article_publisher":"https:\/\/www.facebook.com\/javacodegeeks","article_published_time":"2020-03-17T13:00:19+00:00","article_modified_time":"2021-05-25T13:59:58+00:00","og_image":[{"width":150,"height":150,"url":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2012\/12\/java-logo.jpg","type":"image\/jpeg"}],"author":"Mary Zheng","twitter_card":"summary_large_image","twitter_creator":"@javacodegeeks","twitter_site":"@javacodegeeks","twitter_misc":{"Written by":"Mary Zheng","Est. reading time":"14 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/examples.javacodegeeks.com\/java-unit-testing-tutorial\/#article","isPartOf":{"@id":"https:\/\/examples.javacodegeeks.com\/java-unit-testing-tutorial\/"},"author":{"name":"Mary Zheng","@id":"https:\/\/examples.javacodegeeks.com\/#\/schema\/person\/8a2034fbabcb20a9396e9819261855ae"},"headline":"Java Unit Testing Tutorial","datePublished":"2020-03-17T13:00:19+00:00","dateModified":"2021-05-25T13:59:58+00:00","mainEntityOfPage":{"@id":"https:\/\/examples.javacodegeeks.com\/java-unit-testing-tutorial\/"},"wordCount":1426,"commentCount":0,"publisher":{"@id":"https:\/\/examples.javacodegeeks.com\/#organization"},"image":{"@id":"https:\/\/examples.javacodegeeks.com\/java-unit-testing-tutorial\/#primaryimage"},"thumbnailUrl":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2012\/12\/java-logo.jpg","articleSection":["Core Java"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/examples.javacodegeeks.com\/java-unit-testing-tutorial\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/examples.javacodegeeks.com\/java-unit-testing-tutorial\/","url":"https:\/\/examples.javacodegeeks.com\/java-unit-testing-tutorial\/","name":"Java Unit Testing Tutorial - Java Code Geeks","isPartOf":{"@id":"https:\/\/examples.javacodegeeks.com\/#website"},"primaryImageOfPage":{"@id":"https:\/\/examples.javacodegeeks.com\/java-unit-testing-tutorial\/#primaryimage"},"image":{"@id":"https:\/\/examples.javacodegeeks.com\/java-unit-testing-tutorial\/#primaryimage"},"thumbnailUrl":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2012\/12\/java-logo.jpg","datePublished":"2020-03-17T13:00:19+00:00","dateModified":"2021-05-25T13:59:58+00:00","description":"This is a tutorial for Java unit testing. In this tutorial, I will create a spring boot application which includes test cases written with Junit, Mockito,","breadcrumb":{"@id":"https:\/\/examples.javacodegeeks.com\/java-unit-testing-tutorial\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/examples.javacodegeeks.com\/java-unit-testing-tutorial\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/examples.javacodegeeks.com\/java-unit-testing-tutorial\/#primaryimage","url":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2012\/12\/java-logo.jpg","contentUrl":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2012\/12\/java-logo.jpg","width":150,"height":150,"caption":"Bipartite Graph"},{"@type":"BreadcrumbList","@id":"https:\/\/examples.javacodegeeks.com\/java-unit-testing-tutorial\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/examples.javacodegeeks.com\/"},{"@type":"ListItem","position":2,"name":"Java Development","item":"https:\/\/examples.javacodegeeks.com\/category\/java-development\/"},{"@type":"ListItem","position":3,"name":"Core Java","item":"https:\/\/examples.javacodegeeks.com\/category\/java-development\/core-java\/"},{"@type":"ListItem","position":4,"name":"Java Unit Testing Tutorial"}]},{"@type":"WebSite","@id":"https:\/\/examples.javacodegeeks.com\/#website","url":"https:\/\/examples.javacodegeeks.com\/","name":"Java Code Geeks","description":"Java Examples and Code Snippets","publisher":{"@id":"https:\/\/examples.javacodegeeks.com\/#organization"},"alternateName":"JCG","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/examples.javacodegeeks.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/examples.javacodegeeks.com\/#organization","name":"Exelixis Media P.C.","url":"https:\/\/examples.javacodegeeks.com\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/examples.javacodegeeks.com\/#\/schema\/logo\/image\/","url":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2022\/06\/exelixis-logo.png","contentUrl":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2022\/06\/exelixis-logo.png","width":864,"height":246,"caption":"Exelixis Media P.C."},"image":{"@id":"https:\/\/examples.javacodegeeks.com\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/javacodegeeks","https:\/\/x.com\/javacodegeeks"]},{"@type":"Person","@id":"https:\/\/examples.javacodegeeks.com\/#\/schema\/person\/8a2034fbabcb20a9396e9819261855ae","name":"Mary Zheng","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/examples.javacodegeeks.com\/#\/schema\/person\/image\/","url":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2017\/11\/Mary-Zheng_avatar_1510732235-96x96.jpg","contentUrl":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2017\/11\/Mary-Zheng_avatar_1510732235-96x96.jpg","caption":"Mary Zheng"},"description":"Mary has graduated from Mechanical Engineering department at ShangHai JiaoTong University. She also holds a Master degree in Computer Science from Webster University. During her studies she has been involved with a large number of projects ranging from programming and software engineering. She works as a senior Software Engineer in the telecommunications sector where she acts as a leader and works with others to design, implement, and monitor the software solution.","url":"https:\/\/examples.javacodegeeks.com\/author\/mary-zheng\/"}]}},"_links":{"self":[{"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/posts\/86381","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/users\/140"}],"replies":[{"embeddable":true,"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/comments?post=86381"}],"version-history":[{"count":0,"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/posts\/86381\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/media\/1204"}],"wp:attachment":[{"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/media?parent=86381"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/categories?post=86381"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/tags?post=86381"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}