Download presentation
Presentation is loading. Please wait.
1
Testing with Spring Boot
Unit Testing Testing with Spring Boot Unit Testing SoftUni Team Technical Trainers Software University
2
Table of Contents Unit Testing Repository Layer Service Layer
Entities (Recap) Repositories Service Layer Web Layer Controllers
3
Have a Question? sli.do #JavaWeb
4
Unit Testing
5
What are Unit Tests? individual units of source code are tested to determine whether they are work as intended. System Testing Integration Testing Unit Testing Test System Test Modules Test Methods
6
Why to Test? More reliable code – due to less bugs
Faster development – no need to constantly debug Better maintenance – because of a constant code care Clearer code – code modularity is required to write tests Cheaper – bugs in production cost more
7
Cost in Different Phases
8
Spring Unit Testing pom.xml <dependency>
JUnit — The de-facto standard for unit testing Java applications. Spring Test & Spring Boot Test — Utilities and integration test support for Spring Boot applications. AssertJ — A fluent assertion library. Hamcrest — A library of matcher objects (also known as constraints or predicates). Mockito — A Java mocking framework. JSONassert — An assertion library for JSON. JsonPath — XPath for JSON. pom.xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency>
9
Entity Testing
10
Problem 1 How to test? User.java @Entity
public abstract class User implements UserDetails { public void addRole(Role role){ this.getAuthorities().add(role); } How to test?
11
Spring Boot Test Utilities
Entity Test (1) UserTest.java @RunWith(SpringRunner.class) public class UserTest { private User user; @Mock private Role role; @Before public void setUp() throws Exception { //Arrange this.user = new BasicUser(); when(this.role.getAuthority()).thenReturn("ROLE_USER"); } … Spring Boot Test Utilities
12
Entity Test (2) UserTest.java @RunWith(SpringRunner.class)
public class UserTest { @Test public void addRoleWhenRoleExists_ShouldAddRole() throws Exception { //Act this.user.addRole(this.role); //Assert Role role = this.user.getAuthorities().iterator().next(); assertEquals(role.getAuthority(), "ROLE_USER"); }
13
Repository Testing
14
Problem 2 How to test? BikeRepository.java @Repository
public interface BikeRepository extends JpaRepository<Bike, Long> { @Query(value = "SELECT b FROM Bike AS b") List<Bike> findAll(); } How to test?
15
Repository Test Spring Boot Test Utilities JPA Test
BikeRepositoryTest.java @RunWith(SpringRunner.class) = NONE) public class BikeRepositoryTest { @Autowired private TestEntityManager testEntityManager; private BikeRepository bikeRepository; @Test public void findAllShouldReturnCorrectSizeList() throws Exception { int listSize = 5; for (int i = 0; i < listSize; i++) { this.testEntityManager.persist(new Bike()); } List<Bike> bikes = this.bikeRepository.findAll(); assertEquals(listSize,bikes.size()); JPA Test Use Standard Database Repository Alternative
16
Repository Test Database
BikeRepositoryTest.java @RunWith(SpringRunner.class) = NONE) public class BikeRepositoryTest { @Autowired private TestEntityManager testEntityManager; } Should we test in production database? Test in in-memory database MySQL HSQL
17
In-Memory Databases (1)
application.properties spring.profiles.active=dev application-dev.properties #Dev Data Source Properties spring.datasource.driverClassName=com.mysql.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/social_demo?useSSL=false&createDatabaseIfNotExist=true spring.datasource.username=root spring.datasource.password=1234
18
In-Memory Databases (2)
application-test.properties spring.jpa.hibernate.ddl-auto=create-drop spring.jpa.database=HSQL spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.HSQLDialect spring.datasource.driverClassName=org.hsqldb.jdbcDriver spring.datasource.url=jdbc:hsqldb:mem:social spring.datasource.username=sa spring.datasource.password=
19
In-Memory Databases (3)
pom.xml <dependency> <groupId>org.hsqldb</groupId> <artifactId>hsqldb</artifactId> <scope>test</scope> </dependency>
20
In-Memory Databases (4)
BikeRepositoryTest.java @RunWith(SpringRunner.class) public class BikeRepositoryTest { @Autowired private TestEntityManager testEntityManager; } Test Profile
21
Exercise: Test User and Bike Repository
22
Service Testing
23
Problem 3 How to test? BikeService.java public interface BikeService {
BikeViewModel findById(long id); List<BikeViewModel> findAll(); Page<BikeViewModel> findAll(Pageable pageable); } How to test?
24
Service Testing (1) Inject in Service Mock a Bean Autowire Service
BikeService.java @RunWith(SpringRunner.class) @SpringBootTest @ActiveProfiles("test") public class BikeServiceTest { @Autowired private ModelMapper modelMapper; @MockBean private BikeRepository bikeRepository; private BikeService bikeService; Inject in Service Mock a Bean Autowire Service
25
Service Testing (2) BikeService.java @Before
public void setUp() throws Exception { Bike bike = new Bike(); bike.setId(1); bike.setModel("BMX"); when(bikeRepository.findOne(1L)).thenReturn(bike); } @Test public void wheUserIdIsProvided_ShouldReturnCorrectModel() throws Exception { BikeViewModel bikeViewModel = this.bikeService.findById(1); assertEquals(bikeViewModel.getModel(),"BMX");
26
Exercise: SocialUser Service
27
Web Layer Testing
28
Problem 4 How to test? BikeService.java
@GetMapping("/bikes/show/{id}") public String showBike(Model long id){ BikeViewModel bikeViewModel = this.bikeService.findById(id); model.addAttribute("bike", bikeViewModel); return "bike-show"; } How to test?
29
Disable Security for Tests
application-test.properties … security.basic.enabled=false Disable Security?
30
Pagination Support (Optional)
Controller Testing (1) BikeControllerTest.java @RunWith(SpringRunner.class) @WebMvcTest(BikeController.class) @ActiveProfiles("test") @EnableSpringDataWebSupport public class BikeControllerTest { @Autowired private MockMvc mvc; @MockBean private BikeService bikeService; @Before public void setUp() throws Exception { BikeViewModel bike = new BikeViewModel(); bike.setId(1); bike.setModel("BMX"); when(bikeService.findById(1)).thenReturn(bike); } Controller Test Pagination Support (Optional)
31
Controller Testing (2) HTTP Status View Test Model Test
BikeControllerTest.java @Test public void showBikeWhenBikeExists_ShouldReturnViewAndModel() throws Exception { this.mvc.perform( get("/bikes/show/1")) .andExpect(status().isOk()) .andExpect(view().name("bike-show")) .andExpect(model().attribute("bike", hasProperty("id", is(1L)))) .andExpect(model().attribute("bike", hasProperty("model", is("BMX")))) .andExpect(model().attribute("bike", hasProperty("gears", is(24)))); } HTTP Status View Test Model Test
32
Controller Testing Exception Handling
BikeControllerTest.java @Test public void showBikeWhenBikeNotExists_ShouldReturnNotFound() throws Exception { this.mvc.perform(get("/bikes/show/2")) .andExpect(status().is4xxClientError()) .andExpect(view().name("exceptions/bike-not-found")); } HTTP Status View Test
33
Summary Unit Testing – critical part of the development process that ensures our application works as expected
34
Web Development Basics – Course Overview
© Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.
35
License This course (slides, examples, demos, videos, homework, etc.) is licensed under the "Creative Commons Attribution- NonCommercial-ShareAlike 4.0 International" license © Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.
36
Free Trainings @ Software University
Software University Foundation – softuni.org Software University – High-Quality Education, Profession and Job for Software Developers softuni.bg Software Facebook facebook.com/SoftwareUniversity Software YouTube youtube.com/SoftwareUniversity Software University Forums – forum.softuni.bg © Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.