In my previous post, I explained how to write unit
tests. In this post, I am going to explain how to write integration tests to service
layer.
This is continuation to my previous post, You can
download previous working application from this link.
Step 1: Create a class by annotating it
with @RunWith and @SpringBootTest annotations.
@RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = App.class) public class EmployeeServiceIntegrationTest { ..... ..... }
SpringJUnit4ClassRunner is a custom extension of
JUnit's BlockJUnit4ClassRunner which provides functionality of the Spring
TestContext Framework to standard JUnit tests.
When a class is annotated with @RunWith or extends a
class annotated with @RunWith, JUnit will invoke the class it references to run
the tests in that class instead of the runner built into Junit.
@ SpringBootTest annotation should be specified on a
test class that runs Spring Boot based tests.
Step 2: Autowire the service class and
use it while testing.
@Autowired
private EmployeeService employeeService;
EmployeeServiceIntegrationTest.java
package com.sample.app.service; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import java.util.Optional; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.sample.app.App; import com.sample.app.model.Employee; @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = App.class) public class EmployeeServiceIntegrationTest { @Autowired private EmployeeService employeeService; @Test public void testCreateEmployee() { Employee emp = new Employee(); emp.setFirstName("Ram"); emp.setLastName("Gurram"); Employee cratedEmp = employeeService.createEmployee(emp); assertEquals(cratedEmp.getFirstName(), "Ram"); assertEquals(cratedEmp.getLastName(), "Gurram"); Optional<Employee> empOptional = employeeService.getEmployee(cratedEmp.getId()); if (!empOptional.isPresent()) { assertFalse("No employee exist with id : " + cratedEmp.getId(), true); } Employee persistedEmp = empOptional.get(); assertEquals(persistedEmp.getFirstName(), "Ram"); assertEquals(persistedEmp.getLastName(), "Gurram"); } }
Total project structure looks like below.
You can download complete working application from
this link.
No comments:
Post a Comment