├── .travis.yml ├── .mvn └── wrapper │ ├── maven-wrapper.jar │ └── maven-wrapper.properties ├── src ├── main │ ├── resources │ │ ├── import.sql │ │ ├── application.yml │ │ └── ehcache3.xml │ └── java │ │ └── org │ │ └── exampledriven │ │ └── springboottestingworkshop │ │ ├── service │ │ ├── BlackBoxService.java │ │ ├── CacheManagerCheck.java │ │ └── PostService.java │ │ ├── SpringBootTestingWorkshopApplication.java │ │ ├── repository │ │ └── PersonRepository.java │ │ ├── domain │ │ ├── Post.java │ │ ├── PersonAndPost.java │ │ └── Person.java │ │ ├── controller │ │ └── PostController.java │ │ └── client │ │ └── PostClient.java └── test │ ├── java │ └── org │ │ └── exampledriven │ │ └── springboottestingworkshop │ │ ├── service │ │ ├── PostServiceMockTest.java │ │ ├── BlackBoxServiceTest.java │ │ ├── PostServiceCacheTest.java │ │ ├── PostServiceStubTestConfigurationTest.java │ │ └── PostServiceStubTestComponentTest.java │ │ ├── solution │ │ ├── TestUtil.java │ │ ├── performance │ │ │ ├── NoSpringTest.java │ │ │ ├── NoWebContextTest.java │ │ │ ├── FullContextTest.java │ │ │ └── ConfigInnerContextTest.java │ │ ├── client │ │ │ ├── PostClientTest.java │ │ │ └── PostClientMockTest.java │ │ ├── service │ │ │ ├── BlackBoxServiceTest.java │ │ │ ├── PostServiceTest.java │ │ │ ├── PostServiceCacheTest.java │ │ │ ├── PostServiceStubTestConfigurationTest.java │ │ │ ├── PostServiceStubTestComponentTest.java │ │ │ └── PostServiceMockTest.java │ │ ├── repository │ │ │ └── PersonRepositoryTest.java │ │ ├── domain │ │ │ └── PersonTest.java │ │ └── controller │ │ │ ├── PostControllerRandomPortTest.java │ │ │ └── PostControllerMockTest.java │ │ ├── controller │ │ ├── PostControllerMockTest.java │ │ └── PostControllerRandomPortTest.java │ │ ├── performance │ │ ├── runner │ │ │ ├── MockitoJUnitRunnerMeasurer.java │ │ │ └── SpringRunnerMeasurer.java │ │ └── FullContextTest.java │ │ ├── repository │ │ └── PersonRepositoryTest.java │ │ ├── domain │ │ └── PersonTest.java │ │ └── client │ │ └── PostClientMockTest.java │ └── resources │ └── posts.json ├── .gitignore ├── README.md ├── pom.xml ├── mvnw.cmd └── mvnw /.travis.yml: -------------------------------------------------------------------------------- 1 | language: java 2 | jdk: oraclejdk8 3 | before_install: 4 | - chmod +x mvnw -------------------------------------------------------------------------------- /.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ExampleDriven/spring-boot-testing-workshop/HEAD/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.5.0/apache-maven-3.5.0-bin.zip 2 | -------------------------------------------------------------------------------- /src/main/resources/import.sql: -------------------------------------------------------------------------------- 1 | INSERT INTO person (id, first_name, last_name) VALUES (1, 'John', 'Doe'); 2 | INSERT INTO person (id, first_name, last_name) VALUES (2, 'John', 'Smith'); 3 | INSERT INTO person (id, first_name, last_name) VALUES (3, 'Jimmy', 'Brown'); -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | target/ 2 | !.mvn/wrapper/maven-wrapper.jar 3 | 4 | ### STS ### 5 | .apt_generated 6 | .classpath 7 | .factorypath 8 | .project 9 | .settings 10 | .springBeans 11 | 12 | ### IntelliJ IDEA ### 13 | .idea 14 | *.iws 15 | *.iml 16 | *.ipr 17 | 18 | ### NetBeans ### 19 | nbproject/private/ 20 | build/ 21 | nbbuild/ 22 | dist/ 23 | nbdist/ 24 | .nb-gradle/ -------------------------------------------------------------------------------- /src/test/java/org/exampledriven/springboottestingworkshop/service/PostServiceMockTest.java: -------------------------------------------------------------------------------- 1 | package org.exampledriven.springboottestingworkshop.service; 2 | 3 | import org.junit.Test; 4 | 5 | /** 6 | * Created by Peter Szanto on 7/3/2017. 7 | */ 8 | public class PostServiceMockTest { 9 | @Test 10 | public void readPersonAndPost() { 11 | //TODO 3 12 | } 13 | 14 | } -------------------------------------------------------------------------------- /src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | logging: 2 | level: 3 | org.hibernate.SQL: DEBUG 4 | org.hibernate.type.descriptor.sql.BasicBinder: TRACE 5 | org.hibernate.type: TRACE 6 | org.exampledriven: DEBUG 7 | 8 | post-service: 9 | url: https://jsonplaceholder.typicode.com/posts?userId={userId} 10 | 11 | spring: 12 | cache: 13 | jcache: 14 | config: classpath:ehcache3.xml -------------------------------------------------------------------------------- /src/main/java/org/exampledriven/springboottestingworkshop/service/BlackBoxService.java: -------------------------------------------------------------------------------- 1 | package org.exampledriven.springboottestingworkshop.service; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | import org.springframework.stereotype.Service; 6 | 7 | /** 8 | * Created by Peter Szanto on 7/4/2017. 9 | */ 10 | @Service 11 | public class BlackBoxService { 12 | 13 | private Logger logger = LoggerFactory.getLogger(this.getClass()); 14 | 15 | public void doUntestableThings() { 16 | logger.debug("Secret processing is done"); 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/org/exampledriven/springboottestingworkshop/SpringBootTestingWorkshopApplication.java: -------------------------------------------------------------------------------- 1 | package org.exampledriven.springboottestingworkshop; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.cache.annotation.EnableCaching; 6 | 7 | @SpringBootApplication 8 | @EnableCaching 9 | public class SpringBootTestingWorkshopApplication { 10 | 11 | public static void main(String[] args) { 12 | SpringApplication.run(SpringBootTestingWorkshopApplication.class, args); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/org/exampledriven/springboottestingworkshop/repository/PersonRepository.java: -------------------------------------------------------------------------------- 1 | package org.exampledriven.springboottestingworkshop.repository; 2 | 3 | import org.exampledriven.springboottestingworkshop.domain.Person; 4 | import org.springframework.data.repository.CrudRepository; 5 | 6 | /** 7 | * Created by Peter Szanto on 7/2/2017. 8 | */ 9 | public interface PersonRepository extends CrudRepository { 10 | 11 | Person findByFirstNameAndLastName(String firstName, String lastName); 12 | 13 | void deleteByFirstNameAndLastName(String firstName, String lastName); 14 | 15 | } 16 | -------------------------------------------------------------------------------- /src/main/resources/ehcache3.xml: -------------------------------------------------------------------------------- 1 | 6 | 7 | 8 | 24 9 | 10 | 200 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /src/test/java/org/exampledriven/springboottestingworkshop/solution/TestUtil.java: -------------------------------------------------------------------------------- 1 | package org.exampledriven.springboottestingworkshop.solution; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.IOException; 5 | import java.io.InputStream; 6 | import java.io.InputStreamReader; 7 | import java.util.stream.Collectors; 8 | 9 | /** 10 | * Created by Peter Szanto on 7/2/2017. 11 | */ 12 | public class TestUtil { 13 | public static String toString(InputStream input) throws IOException { 14 | try (BufferedReader buffer = new BufferedReader(new InputStreamReader(input))) { 15 | return buffer.lines().collect(Collectors.joining("\n")); 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/test/java/org/exampledriven/springboottestingworkshop/controller/PostControllerMockTest.java: -------------------------------------------------------------------------------- 1 | package org.exampledriven.springboottestingworkshop.controller; 2 | 3 | import org.junit.Test; 4 | import org.springframework.beans.factory.annotation.Autowired; 5 | import org.springframework.test.web.servlet.MockMvc; 6 | 7 | import static org.junit.Assert.*; 8 | 9 | /** 10 | * Created by Peter Szanto on 7/4/2017. 11 | */ 12 | public class PostControllerMockTest { 13 | 14 | private static final String JOHN = "John"; 15 | private static final String DOE = "Doe"; 16 | 17 | @Autowired 18 | private MockMvc mockMvc; 19 | 20 | @Test 21 | public void readPost() throws Exception { 22 | //TODO 8 implement this test using webEnvironment = SpringBootTest.WebEnvironment.MOCK 23 | } 24 | 25 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Build Status](https://travis-ci.org/ExampleDriven/spring-boot-testing-workshop.svg?branch=master)](https://travis-ci.org/ExampleDriven/spring-boot-testing-workshop) 2 | 3 | # Spring Boot testing workshop 4 | 5 | This repository is the course material for the Spring Boot testing workshop written by Peter Szanto. 6 | You can contact me here, if you are interested to have this workshop delivered by me : 7 | 8 | https://exampledriven.wordpress.com/contact/ 9 | 10 | The presentation is on [prezi.com](https://prezi.com/nyyggekgq18l/spring-boot-testing-workshop/) 11 | 12 | In this repo each commit adds a new technology and demonstrates how to test it. This covers : 13 | * JPA 14 | * JDBC 15 | * RestClient 16 | * Service 17 | * Controller 18 | * Caching 19 | 20 | The below tools/techniques are used for testing 21 | 22 | * Spy 23 | * Mock 24 | * Stub 25 | * Spring's @Test* annotation 26 | * JUnit 27 | * Test NG 28 | -------------------------------------------------------------------------------- /src/test/java/org/exampledriven/springboottestingworkshop/service/BlackBoxServiceTest.java: -------------------------------------------------------------------------------- 1 | package org.exampledriven.springboottestingworkshop.service; 2 | 3 | import org.junit.Rule; 4 | import org.junit.Test; 5 | import org.junit.runner.RunWith; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.boot.test.context.SpringBootTest; 8 | import org.springframework.boot.test.rule.OutputCapture; 9 | import org.springframework.test.context.junit4.SpringRunner; 10 | 11 | import static org.assertj.core.api.Assertions.assertThat; 12 | 13 | /** 14 | * Created by Peter Szanto on 7/4/2017. 15 | */ 16 | public class BlackBoxServiceTest { 17 | 18 | @Rule 19 | public OutputCapture capture = new OutputCapture(); 20 | 21 | @Autowired 22 | private BlackBoxService blackBoxService; 23 | 24 | @Test 25 | public void doUntestableThings() { 26 | //TODO 10 27 | } 28 | 29 | } -------------------------------------------------------------------------------- /src/test/java/org/exampledriven/springboottestingworkshop/performance/runner/MockitoJUnitRunnerMeasurer.java: -------------------------------------------------------------------------------- 1 | package org.exampledriven.springboottestingworkshop.performance.runner; 2 | 3 | import org.junit.runner.notification.RunNotifier; 4 | import org.mockito.runners.MockitoJUnitRunner; 5 | 6 | import java.lang.reflect.InvocationTargetException; 7 | import java.util.Date; 8 | 9 | public class MockitoJUnitRunnerMeasurer extends MockitoJUnitRunner { 10 | 11 | private Date start; 12 | 13 | public MockitoJUnitRunnerMeasurer(Class klass) throws InvocationTargetException { 14 | 15 | super(klass); 16 | start = new Date(); 17 | } 18 | 19 | @Override 20 | public void run(RunNotifier notifier) { 21 | 22 | super.run(notifier); 23 | long durationMillis = new Date().getTime() - start.getTime(); 24 | System.out.println("\n-------\nDuration - 00:" + (durationMillis / 1000) + ":" + (durationMillis % 1000) + "\n-------"); 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/org/exampledriven/springboottestingworkshop/domain/Post.java: -------------------------------------------------------------------------------- 1 | package org.exampledriven.springboottestingworkshop.domain; 2 | 3 | /** 4 | * Created by Peter Szanto on 7/2/2017. 5 | */ 6 | public class Post { 7 | 8 | private int userId; 9 | private int id; 10 | private String title; 11 | private String body; 12 | 13 | public int getUserId() { 14 | return userId; 15 | } 16 | 17 | public void setUserId(int userId) { 18 | this.userId = userId; 19 | } 20 | 21 | public int getId() { 22 | return id; 23 | } 24 | 25 | public void setId(int id) { 26 | this.id = id; 27 | } 28 | 29 | public String getTitle() { 30 | return title; 31 | } 32 | 33 | public void setTitle(String title) { 34 | this.title = title; 35 | } 36 | 37 | public String getBody() { 38 | return body; 39 | } 40 | 41 | public void setBody(String body) { 42 | this.body = body; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/test/java/org/exampledriven/springboottestingworkshop/performance/runner/SpringRunnerMeasurer.java: -------------------------------------------------------------------------------- 1 | package org.exampledriven.springboottestingworkshop.performance.runner; 2 | 3 | import org.junit.runner.notification.RunNotifier; 4 | import org.junit.runners.model.InitializationError; 5 | import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 6 | 7 | import java.util.Date; 8 | 9 | public class SpringRunnerMeasurer extends SpringJUnit4ClassRunner { 10 | 11 | 12 | private Date start; 13 | 14 | public SpringRunnerMeasurer(Class klass) throws InitializationError { 15 | 16 | super(klass); 17 | start = new Date(); 18 | } 19 | 20 | @Override 21 | public void run(RunNotifier notifier) { 22 | super.run(notifier); 23 | long durationMillis = new Date().getTime() - start.getTime(); 24 | System.out.println("\n-------\nDuration - 00:" + (durationMillis / 1000) + ":" + (durationMillis % 1000) + "\n-------"); 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/org/exampledriven/springboottestingworkshop/controller/PostController.java: -------------------------------------------------------------------------------- 1 | package org.exampledriven.springboottestingworkshop.controller; 2 | 3 | import org.exampledriven.springboottestingworkshop.domain.PersonAndPost; 4 | import org.exampledriven.springboottestingworkshop.service.PostService; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.web.bind.annotation.GetMapping; 7 | import org.springframework.web.bind.annotation.RequestParam; 8 | import org.springframework.web.bind.annotation.RestController; 9 | 10 | /** 11 | * Created by Peter Szanto on 7/4/2017. 12 | */ 13 | @RestController 14 | public class PostController { 15 | 16 | @Autowired 17 | private PostService postService; 18 | 19 | @GetMapping("/post") 20 | public PersonAndPost readPost(@RequestParam("firstName") String firstName, @RequestParam("lastName") String lastName) { 21 | return postService.readPersonAndPost(firstName, lastName); 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /src/test/java/org/exampledriven/springboottestingworkshop/solution/performance/NoSpringTest.java: -------------------------------------------------------------------------------- 1 | package org.exampledriven.springboottestingworkshop.solution.performance; 2 | 3 | import org.exampledriven.springboottestingworkshop.client.PostClient; 4 | import org.exampledriven.springboottestingworkshop.repository.PersonRepository; 5 | import org.exampledriven.springboottestingworkshop.service.PostService; 6 | import org.exampledriven.springboottestingworkshop.performance.runner.MockitoJUnitRunnerMeasurer; 7 | import org.junit.Test; 8 | import org.junit.runner.RunWith; 9 | import org.mockito.InjectMocks; 10 | import org.mockito.Mock; 11 | 12 | import static org.junit.Assert.assertEquals; 13 | import static org.junit.Assert.assertNotNull; 14 | 15 | /** 16 | * Created by Peter Szanto on 7/3/2017. 17 | */ 18 | @RunWith(MockitoJUnitRunnerMeasurer.class) 19 | public class NoSpringTest { 20 | 21 | @Mock 22 | private PersonRepository personRepositoryMock; 23 | 24 | @Mock 25 | private PostClient postClientMock; 26 | 27 | @InjectMocks 28 | private PostService postService; 29 | 30 | @Test 31 | public void testBeans() { 32 | assertNotNull(postService); 33 | } 34 | 35 | } 36 | 37 | -------------------------------------------------------------------------------- /src/main/java/org/exampledriven/springboottestingworkshop/service/CacheManagerCheck.java: -------------------------------------------------------------------------------- 1 | 2 | package org.exampledriven.springboottestingworkshop.service; 3 | 4 | import org.slf4j.Logger; 5 | import org.slf4j.LoggerFactory; 6 | import org.springframework.boot.CommandLineRunner; 7 | import org.springframework.cache.CacheManager; 8 | import org.springframework.stereotype.Component; 9 | 10 | @Component 11 | public class CacheManagerCheck implements CommandLineRunner { 12 | 13 | private static final Logger logger = LoggerFactory.getLogger(CacheManagerCheck.class); 14 | 15 | private final CacheManager cacheManager; 16 | 17 | public CacheManagerCheck(CacheManager cacheManager) { 18 | this.cacheManager = cacheManager; 19 | } 20 | 21 | @Override 22 | public void run(String... strings) throws Exception { 23 | 24 | logger.info("========================================================="); 25 | logger.info("Using cache manager: " + this.cacheManager.getClass().getName()); 26 | logger.info("Configured cache names are"); 27 | cacheManager.getCacheNames().forEach(cacheName -> logger.info(" - " + cacheName) ); 28 | logger.info("========================================================="); 29 | 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /src/test/java/org/exampledriven/springboottestingworkshop/solution/client/PostClientTest.java: -------------------------------------------------------------------------------- 1 | package org.exampledriven.springboottestingworkshop.solution.client; 2 | 3 | import org.exampledriven.springboottestingworkshop.client.PostClient; 4 | import org.exampledriven.springboottestingworkshop.domain.Post; 5 | import org.junit.Test; 6 | import org.junit.runner.RunWith; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.boot.test.autoconfigure.web.client.AutoConfigureMockRestServiceServer; 9 | import org.springframework.boot.test.autoconfigure.web.client.RestClientTest; 10 | import org.springframework.test.context.junit4.SpringRunner; 11 | 12 | import java.util.List; 13 | 14 | import static org.junit.Assert.*; 15 | 16 | /** 17 | * Created by Peter Szanto on 7/2/2017. 18 | */ 19 | @RunWith(SpringRunner.class) 20 | @RestClientTest(PostClient.class) 21 | @AutoConfigureMockRestServiceServer(enabled = false) 22 | public class PostClientTest { 23 | 24 | @Autowired 25 | private PostClient postClient; 26 | 27 | @Test 28 | public void readPosts() { 29 | List posts = postClient.readPosts(1); 30 | assertEquals(10, posts.size()); 31 | } 32 | 33 | } -------------------------------------------------------------------------------- /src/test/java/org/exampledriven/springboottestingworkshop/repository/PersonRepositoryTest.java: -------------------------------------------------------------------------------- 1 | package org.exampledriven.springboottestingworkshop.repository; 2 | 3 | import org.exampledriven.springboottestingworkshop.domain.Person; 4 | import org.exampledriven.springboottestingworkshop.repository.PersonRepository; 5 | import org.junit.Test; 6 | import org.junit.runner.RunWith; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; 9 | import org.springframework.test.context.junit4.SpringRunner; 10 | 11 | import static org.junit.Assert.*; 12 | 13 | /** 14 | * Created by Peter Szanto on 7/2/2017. 15 | */ 16 | //@RunWith(SpringRunner.class) 17 | //@DataJpaTest 18 | public class PersonRepositoryTest { 19 | 20 | //Hint: check all possible values in import.sql 21 | private static final String JOHN = "John"; 22 | private static final String DOE = "Doe"; 23 | 24 | //@Autowired 25 | //private PersonRepository personRepository; 26 | 27 | @Test 28 | public void findByFirstNameAndLastName() { 29 | //TODO 1 30 | } 31 | 32 | @Test 33 | public void deleteByFirstNameAndLastName() { 34 | //TODO 1 35 | } 36 | 37 | } -------------------------------------------------------------------------------- /src/test/java/org/exampledriven/springboottestingworkshop/solution/performance/NoWebContextTest.java: -------------------------------------------------------------------------------- 1 | package org.exampledriven.springboottestingworkshop.solution.performance; 2 | 3 | import org.exampledriven.springboottestingworkshop.service.PostService; 4 | import org.exampledriven.springboottestingworkshop.performance.runner.SpringRunnerMeasurer; 5 | import org.junit.Test; 6 | import org.junit.runner.RunWith; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.boot.test.context.SpringBootTest; 9 | import org.springframework.context.ApplicationContext; 10 | 11 | import static org.junit.Assert.assertEquals; 12 | import static org.junit.Assert.assertNotNull; 13 | 14 | /** 15 | * Created by Peter Szanto on 7/3/2017. 16 | */ 17 | 18 | @RunWith(SpringRunnerMeasurer.class) 19 | @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE) 20 | public class NoWebContextTest { 21 | 22 | @Autowired 23 | private ApplicationContext context; 24 | 25 | @Autowired 26 | private PostService postService; 27 | 28 | @Test 29 | public void testBeans() { 30 | 31 | assertNotNull(postService); 32 | assertEquals(118, context.getBeanDefinitionCount()); 33 | 34 | } 35 | 36 | } -------------------------------------------------------------------------------- /src/test/java/org/exampledriven/springboottestingworkshop/solution/performance/FullContextTest.java: -------------------------------------------------------------------------------- 1 | package org.exampledriven.springboottestingworkshop.solution.performance; 2 | 3 | import org.exampledriven.springboottestingworkshop.service.PostService; 4 | import org.exampledriven.springboottestingworkshop.performance.runner.SpringRunnerMeasurer; 5 | import org.junit.Test; 6 | import org.junit.runner.RunWith; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.boot.test.context.SpringBootTest; 9 | import org.springframework.context.ApplicationContext; 10 | 11 | import static org.junit.Assert.assertEquals; 12 | import static org.junit.Assert.assertNotNull; 13 | 14 | /** 15 | * Created by Peter Szanto on 7/3/2017. 16 | */ 17 | 18 | @RunWith(SpringRunnerMeasurer.class) 19 | @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) 20 | public class FullContextTest { 21 | 22 | @Autowired 23 | private ApplicationContext context; 24 | 25 | @Autowired 26 | private PostService postService; 27 | 28 | @Test 29 | public void testBeans() { 30 | 31 | assertNotNull(postService); 32 | assertEquals(191, context.getBeanDefinitionCount()); 33 | 34 | } 35 | 36 | } -------------------------------------------------------------------------------- /src/test/java/org/exampledriven/springboottestingworkshop/solution/service/BlackBoxServiceTest.java: -------------------------------------------------------------------------------- 1 | package org.exampledriven.springboottestingworkshop.solution.service; 2 | 3 | import org.exampledriven.springboottestingworkshop.service.BlackBoxService; 4 | import org.junit.Rule; 5 | import org.junit.Test; 6 | import org.junit.runner.RunWith; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.boot.test.context.SpringBootTest; 9 | import org.springframework.boot.test.rule.OutputCapture; 10 | import org.springframework.test.context.junit4.SpringRunner; 11 | 12 | import java.util.List; 13 | 14 | import static org.assertj.core.api.Assertions.assertThat; 15 | import static org.junit.Assert.*; 16 | 17 | /** 18 | * Created by Peter Szanto on 7/4/2017. 19 | */ 20 | @RunWith(SpringRunner.class) 21 | @SpringBootTest 22 | public class BlackBoxServiceTest { 23 | 24 | @Rule 25 | public OutputCapture capture = new OutputCapture(); 26 | 27 | @Autowired 28 | private BlackBoxService blackBoxService; 29 | 30 | @Test 31 | public void doUntestableThings() { 32 | blackBoxService.doUntestableThings(); 33 | assertThat(capture.toString()).contains("Secret processing is done"); 34 | } 35 | 36 | } -------------------------------------------------------------------------------- /src/test/java/org/exampledriven/springboottestingworkshop/controller/PostControllerRandomPortTest.java: -------------------------------------------------------------------------------- 1 | package org.exampledriven.springboottestingworkshop.controller; 2 | 3 | import org.exampledriven.springboottestingworkshop.domain.PersonAndPost; 4 | import org.exampledriven.springboottestingworkshop.domain.Post; 5 | import org.junit.Test; 6 | import org.junit.runner.RunWith; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.boot.test.context.SpringBootTest; 9 | import org.springframework.boot.test.web.client.TestRestTemplate; 10 | import org.springframework.test.context.junit4.SpringRunner; 11 | 12 | import static org.junit.Assert.assertEquals; 13 | import static org.junit.Assert.assertTrue; 14 | 15 | /** 16 | * Created by Peter Szanto on 7/4/2017. 17 | */ 18 | 19 | public class PostControllerRandomPortTest { 20 | private static final String JOHN = "John"; 21 | private static final String DOE = "Doe"; 22 | private static final int USER_ID = 1; 23 | 24 | @Autowired 25 | private TestRestTemplate testRestTemplate; 26 | 27 | @Test 28 | public void readPost() throws Exception { 29 | //TODO 9 implement this test using webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT 30 | 31 | } 32 | 33 | } -------------------------------------------------------------------------------- /src/main/java/org/exampledriven/springboottestingworkshop/domain/PersonAndPost.java: -------------------------------------------------------------------------------- 1 | package org.exampledriven.springboottestingworkshop.domain; 2 | 3 | import java.util.List; 4 | import java.util.Objects; 5 | 6 | /** 7 | * Created by Peter Szanto on 7/3/2017. 8 | */ 9 | public class PersonAndPost { 10 | 11 | private Person person; 12 | private List posts; 13 | 14 | public Person getPerson() { 15 | return person; 16 | } 17 | 18 | public void setPerson(Person person) { 19 | this.person = person; 20 | } 21 | 22 | public List getPosts() { 23 | return posts; 24 | } 25 | 26 | public void setPosts(List posts) { 27 | this.posts = posts; 28 | } 29 | 30 | @Override 31 | public boolean equals(Object o) { 32 | if (this == o) return true; 33 | if (o == null || getClass() != o.getClass()) return false; 34 | PersonAndPost that = (PersonAndPost) o; 35 | return Objects.equals(person, that.person) && 36 | Objects.equals(posts, that.posts); 37 | } 38 | 39 | @Override 40 | public int hashCode() { 41 | return Objects.hash(person, posts); 42 | } 43 | 44 | @Override 45 | public String toString() { 46 | return "PersonAndPost{" + 47 | "person=" + person + 48 | ", posts=" + posts + 49 | '}'; 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/test/java/org/exampledriven/springboottestingworkshop/domain/PersonTest.java: -------------------------------------------------------------------------------- 1 | package org.exampledriven.springboottestingworkshop.domain; 2 | 3 | 4 | import org.exampledriven.springboottestingworkshop.domain.Person; 5 | import org.junit.Before; 6 | import org.junit.Test; 7 | import org.junit.runner.RunWith; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.boot.test.autoconfigure.json.JsonTest; 10 | import org.springframework.boot.test.json.JacksonTester; 11 | import org.springframework.test.context.junit4.SpringRunner; 12 | 13 | import static org.assertj.core.api.Assertions.assertThat; 14 | 15 | /** 16 | * Created by Peter Szanto on 7/4/2017. 17 | */ 18 | @RunWith(SpringRunner.class) 19 | @JsonTest 20 | public class PersonTest { 21 | 22 | private static final String PERSON_JSON = "{\"id\":0, \"firstName\": \"First\", \"lastName\":\"Last\"}"; 23 | 24 | @Autowired 25 | private JacksonTester personJacksonTester; 26 | 27 | private Person person; 28 | 29 | @Before 30 | public void setUp() { 31 | person = new Person(); 32 | person.setFirstName("First"); 33 | person.setLastName("Last"); 34 | } 35 | 36 | @Test 37 | public void testSerialize() throws Exception { 38 | 39 | //TODO 7 40 | 41 | } 42 | 43 | @Test 44 | public void testDeserialize() throws Exception { 45 | 46 | //TODO 7 47 | 48 | } 49 | 50 | } -------------------------------------------------------------------------------- /src/main/java/org/exampledriven/springboottestingworkshop/service/PostService.java: -------------------------------------------------------------------------------- 1 | package org.exampledriven.springboottestingworkshop.service; 2 | 3 | import org.exampledriven.springboottestingworkshop.client.PostClient; 4 | import org.exampledriven.springboottestingworkshop.domain.Person; 5 | import org.exampledriven.springboottestingworkshop.domain.PersonAndPost; 6 | import org.exampledriven.springboottestingworkshop.domain.Post; 7 | import org.exampledriven.springboottestingworkshop.repository.PersonRepository; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.stereotype.Service; 10 | 11 | import java.util.List; 12 | 13 | /** 14 | * Created by Peter Szanto on 7/3/2017. 15 | */ 16 | @Service 17 | public class PostService { 18 | @Autowired 19 | private PersonRepository personRepository; 20 | 21 | @Autowired 22 | private PostClient postClient; 23 | 24 | public PersonAndPost readPersonAndPost(String firstName, String lastName) { 25 | 26 | Person person = personRepository.findByFirstNameAndLastName(firstName, lastName); 27 | 28 | if (person != null) { 29 | List posts = postClient.readPosts(person.getId()); 30 | PersonAndPost personAndPost = new PersonAndPost(); 31 | personAndPost.setPosts(posts); 32 | personAndPost.setPerson(person); 33 | 34 | return personAndPost; 35 | } 36 | 37 | return null; 38 | 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/test/java/org/exampledriven/springboottestingworkshop/service/PostServiceCacheTest.java: -------------------------------------------------------------------------------- 1 | package org.exampledriven.springboottestingworkshop.service; 2 | 3 | import org.exampledriven.springboottestingworkshop.client.PostClient; 4 | import org.exampledriven.springboottestingworkshop.domain.PersonAndPost; 5 | import org.junit.Before; 6 | import org.junit.Test; 7 | import org.junit.runner.RunWith; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.boot.test.context.SpringBootTest; 10 | import org.springframework.boot.test.mock.mockito.SpyBean; 11 | import org.springframework.cache.CacheManager; 12 | import org.springframework.test.context.junit4.SpringRunner; 13 | 14 | import static org.junit.Assert.assertEquals; 15 | import static org.mockito.Mockito.times; 16 | import static org.mockito.Mockito.verify; 17 | 18 | /** 19 | * Created by Peter Szanto on 7/3/2017. 20 | */ 21 | 22 | @RunWith(SpringRunner.class) 23 | @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE) 24 | public class PostServiceCacheTest { 25 | 26 | private static final String JOHN = "John"; 27 | private static final String DOE = "Doe"; 28 | 29 | @Autowired 30 | private PostService postService; 31 | 32 | @Test 33 | public void readPersonAndPost() { 34 | 35 | PersonAndPost personFromDB = postService.readPersonAndPost(JOHN, DOE); 36 | 37 | //TODO 6 create a SpyBean of PostClient call PostService multiple time, verify PostClient 38 | 39 | } 40 | 41 | } -------------------------------------------------------------------------------- /src/test/java/org/exampledriven/springboottestingworkshop/solution/service/PostServiceTest.java: -------------------------------------------------------------------------------- 1 | package org.exampledriven.springboottestingworkshop.solution.service; 2 | 3 | import org.exampledriven.springboottestingworkshop.domain.Person; 4 | import org.exampledriven.springboottestingworkshop.domain.PersonAndPost; 5 | import org.exampledriven.springboottestingworkshop.service.PostService; 6 | import org.junit.Test; 7 | import org.junit.runner.RunWith; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.boot.test.context.SpringBootTest; 10 | import org.springframework.test.context.junit4.SpringRunner; 11 | 12 | import static org.junit.Assert.*; 13 | 14 | /** 15 | * Created by Peter Szanto on 7/3/2017. 16 | */ 17 | 18 | @RunWith(SpringRunner.class) 19 | @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE) 20 | public class PostServiceTest { 21 | 22 | @Autowired 23 | private PostService postService; 24 | 25 | @Test 26 | public void readPersonAndPost() throws Exception { 27 | Person expectedPerson = new Person(); 28 | expectedPerson.setFirstName("John"); 29 | expectedPerson.setLastName("Doe"); 30 | 31 | PersonAndPost actual = postService.readPersonAndPost(expectedPerson.getFirstName(), expectedPerson.getLastName()); 32 | 33 | assertEquals(expectedPerson.getFirstName(), actual.getPerson().getFirstName()); 34 | assertEquals(expectedPerson.getLastName(), actual.getPerson().getLastName()); 35 | 36 | assertEquals(10, actual.getPosts().size()); 37 | } 38 | 39 | } -------------------------------------------------------------------------------- /src/main/java/org/exampledriven/springboottestingworkshop/client/PostClient.java: -------------------------------------------------------------------------------- 1 | package org.exampledriven.springboottestingworkshop.client; 2 | 3 | import org.exampledriven.springboottestingworkshop.domain.Post; 4 | import org.slf4j.Logger; 5 | import org.slf4j.LoggerFactory; 6 | import org.springframework.beans.factory.annotation.Value; 7 | import org.springframework.boot.web.client.RestTemplateBuilder; 8 | import org.springframework.cache.annotation.Cacheable; 9 | import org.springframework.core.ParameterizedTypeReference; 10 | import org.springframework.http.HttpMethod; 11 | import org.springframework.stereotype.Component; 12 | import org.springframework.web.client.RestTemplate; 13 | 14 | import java.util.List; 15 | 16 | /** 17 | * Created by Peter Szanto on 7/2/2017. 18 | */ 19 | @Component 20 | public class PostClient { 21 | 22 | private Logger logger = LoggerFactory.getLogger(this.getClass()); 23 | 24 | private final RestTemplate restTemplate; 25 | 26 | public PostClient(RestTemplateBuilder restTemplateBuilder) { 27 | this.restTemplate = restTemplateBuilder.build(); 28 | } 29 | 30 | @Value("${post-service.url}") 31 | private String url; 32 | 33 | @Cacheable("post") 34 | public List readPosts(int userId) { 35 | 36 | logger.debug("Calling " + url + "with " + userId); 37 | 38 | return restTemplate.exchange( 39 | url, 40 | HttpMethod.GET, 41 | null, 42 | new ParameterizedTypeReference>() {}, 43 | userId 44 | ).getBody(); 45 | } 46 | 47 | } -------------------------------------------------------------------------------- /src/test/java/org/exampledriven/springboottestingworkshop/solution/repository/PersonRepositoryTest.java: -------------------------------------------------------------------------------- 1 | package org.exampledriven.springboottestingworkshop.solution.repository; 2 | 3 | import org.exampledriven.springboottestingworkshop.domain.Person; 4 | import org.exampledriven.springboottestingworkshop.repository.PersonRepository; 5 | import org.junit.Test; 6 | import org.junit.runner.RunWith; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; 9 | import org.springframework.test.context.junit4.SpringRunner; 10 | 11 | import static org.junit.Assert.*; 12 | 13 | /** 14 | * Created by Peter Szanto on 7/2/2017. 15 | */ 16 | @RunWith(SpringRunner.class) 17 | @DataJpaTest 18 | public class PersonRepositoryTest { 19 | 20 | private static final String JOHN = "John"; 21 | private static final String DOE = "Doe"; 22 | 23 | @Autowired 24 | private PersonRepository personRepository; 25 | 26 | @Test 27 | public void findByFirstNameAndLastName() { 28 | 29 | Person expected = new Person(); 30 | expected.setId(1); 31 | expected.setFirstName(JOHN); 32 | expected.setLastName(DOE); 33 | 34 | assertEquals(expected, personRepository.findByFirstNameAndLastName(expected.getFirstName(), expected.getLastName())); 35 | } 36 | 37 | @Test 38 | public void deleteByFirstNameAndLastName() { 39 | 40 | personRepository.deleteByFirstNameAndLastName(JOHN, DOE); 41 | 42 | assertNull(personRepository.findByFirstNameAndLastName(JOHN, DOE)); 43 | } 44 | 45 | } -------------------------------------------------------------------------------- /src/test/java/org/exampledriven/springboottestingworkshop/client/PostClientMockTest.java: -------------------------------------------------------------------------------- 1 | package org.exampledriven.springboottestingworkshop.client; 2 | 3 | 4 | import org.exampledriven.springboottestingworkshop.client.PostClient; 5 | import org.exampledriven.springboottestingworkshop.domain.Post; 6 | import org.exampledriven.springboottestingworkshop.solution.TestUtil; 7 | import org.junit.Test; 8 | import org.junit.runner.RunWith; 9 | import org.springframework.beans.factory.annotation.Autowired; 10 | import org.springframework.beans.factory.annotation.Value; 11 | import org.springframework.boot.test.autoconfigure.web.client.RestClientTest; 12 | import org.springframework.core.io.Resource; 13 | import org.springframework.http.MediaType; 14 | import org.springframework.test.annotation.DirtiesContext; 15 | import org.springframework.test.context.junit4.SpringRunner; 16 | import org.springframework.test.web.client.MockRestServiceServer; 17 | 18 | import java.util.List; 19 | 20 | import static org.junit.Assert.assertEquals; 21 | import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo; 22 | import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess; 23 | 24 | /** 25 | * Created by Peter Szanto on 7/2/2017. 26 | */ 27 | @RunWith(SpringRunner.class) 28 | @RestClientTest(PostClient.class) 29 | public class PostClientMockTest { 30 | 31 | @Autowired 32 | private PostClient postClient; 33 | 34 | @Autowired 35 | private MockRestServiceServer mockRestServiceServer; 36 | 37 | @Value("posts.json") 38 | private Resource postsJson; 39 | 40 | @Test 41 | public void readPosts() throws Exception { 42 | 43 | String mockJsonResponse = TestUtil.toString(postsJson.getInputStream()); 44 | 45 | //TODO 2 46 | 47 | } 48 | 49 | } -------------------------------------------------------------------------------- /src/test/java/org/exampledriven/springboottestingworkshop/solution/performance/ConfigInnerContextTest.java: -------------------------------------------------------------------------------- 1 | package org.exampledriven.springboottestingworkshop.solution.performance; 2 | 3 | import org.exampledriven.springboottestingworkshop.client.PostClient; 4 | import org.exampledriven.springboottestingworkshop.repository.PersonRepository; 5 | import org.exampledriven.springboottestingworkshop.service.PostService; 6 | import org.exampledriven.springboottestingworkshop.performance.runner.SpringRunnerMeasurer; 7 | import org.junit.Test; 8 | import org.junit.runner.RunWith; 9 | import org.springframework.beans.factory.annotation.Autowired; 10 | import org.springframework.boot.test.context.SpringBootTest; 11 | import org.springframework.boot.test.mock.mockito.MockBean; 12 | import org.springframework.context.ApplicationContext; 13 | import org.springframework.context.annotation.Configuration; 14 | 15 | import static org.junit.Assert.assertEquals; 16 | import static org.junit.Assert.assertNotNull; 17 | 18 | /** 19 | * Created by Peter Szanto on 7/3/2017. 20 | */ 21 | 22 | @RunWith(SpringRunnerMeasurer.class) 23 | @SpringBootTest(classes = {ConfigInnerContextTest.Config.class, PostService.class}) 24 | public class ConfigInnerContextTest { 25 | 26 | @MockBean 27 | private PersonRepository personRepositoryMock; 28 | 29 | @MockBean 30 | private PostClient postClientMock; 31 | 32 | @Autowired 33 | private ApplicationContext context; 34 | 35 | @Autowired 36 | private PostService postService; 37 | 38 | @Test 39 | public void testBeans() { 40 | 41 | assertNotNull(postService); 42 | assertEquals(14, context.getBeanDefinitionCount()); 43 | 44 | } 45 | 46 | //nested @Configuration replaces the application’s primary configuration 47 | @Configuration 48 | static class Config { 49 | 50 | } 51 | 52 | } -------------------------------------------------------------------------------- /src/test/java/org/exampledriven/springboottestingworkshop/solution/domain/PersonTest.java: -------------------------------------------------------------------------------- 1 | package org.exampledriven.springboottestingworkshop.solution.domain; 2 | 3 | import org.exampledriven.springboottestingworkshop.domain.Person; 4 | import org.junit.Before; 5 | import org.junit.Test; 6 | import org.junit.runner.RunWith; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.boot.test.autoconfigure.json.JsonTest; 9 | import org.springframework.boot.test.json.JacksonTester; 10 | import org.springframework.test.context.junit4.SpringRunner; 11 | 12 | import static org.assertj.core.api.Assertions.assertThat; 13 | 14 | /** 15 | * Created by Peter Szanto on 7/4/2017. 16 | */ 17 | @RunWith(SpringRunner.class) 18 | @JsonTest 19 | public class PersonTest { 20 | 21 | private static final String PERSON_JSON = "{\"id\":0, \"firstName\": \"First\", \"lastName\":\"Last\"}"; 22 | 23 | @Autowired 24 | private JacksonTester personJacksonTester; 25 | 26 | private Person person; 27 | 28 | @Before 29 | public void setUp() { 30 | person = new Person(); 31 | person.setFirstName("First"); 32 | person.setLastName("Last"); 33 | } 34 | 35 | @Test 36 | public void testSerialize() throws Exception { 37 | 38 | assertThat(personJacksonTester.write(person)).isEqualToJson(PERSON_JSON); 39 | // Or use JSON path based assertions 40 | assertThat(personJacksonTester.write(person)).hasJsonPathStringValue("@.firstName"); 41 | assertThat(personJacksonTester.write(person)).extractingJsonPathStringValue("@.firstName").isEqualTo("First"); 42 | } 43 | 44 | @Test 45 | public void testDeserialize() throws Exception { 46 | String content = PERSON_JSON; 47 | assertThat(personJacksonTester.parse(content)).isEqualTo(person); 48 | assertThat(personJacksonTester.parseObject(content).getFirstName()).isEqualTo("First"); 49 | } 50 | 51 | } -------------------------------------------------------------------------------- /src/main/java/org/exampledriven/springboottestingworkshop/domain/Person.java: -------------------------------------------------------------------------------- 1 | package org.exampledriven.springboottestingworkshop.domain; 2 | 3 | import javax.persistence.Column; 4 | import javax.persistence.Entity; 5 | import javax.persistence.GeneratedValue; 6 | import javax.persistence.Id; 7 | import java.util.Objects; 8 | 9 | /** 10 | * Created by Peter Szanto on 7/2/2017. 11 | */ 12 | @Entity 13 | public class Person { 14 | 15 | @Id 16 | @GeneratedValue 17 | private int id; 18 | 19 | @Column(name = "first_name") 20 | private String firstName; 21 | 22 | @Column(name = "last_name") 23 | private String lastName; 24 | 25 | public int getId() { 26 | return id; 27 | } 28 | 29 | public void setId(int id) { 30 | this.id = id; 31 | } 32 | 33 | public String getFirstName() { 34 | return firstName; 35 | } 36 | 37 | public void setFirstName(String firstName) { 38 | this.firstName = firstName; 39 | } 40 | 41 | public String getLastName() { 42 | return lastName; 43 | } 44 | 45 | public void setLastName(String lastName) { 46 | this.lastName = lastName; 47 | } 48 | 49 | @Override 50 | public boolean equals(Object o) { 51 | if (this == o) return true; 52 | if (o == null || getClass() != o.getClass()) return false; 53 | Person person = (Person) o; 54 | return id == person.id && 55 | Objects.equals(firstName, person.firstName) && 56 | Objects.equals(lastName, person.lastName); 57 | } 58 | 59 | @Override 60 | public int hashCode() { 61 | return Objects.hash(id, firstName, lastName); 62 | } 63 | 64 | @Override 65 | public String toString() { 66 | return "Person{" + 67 | "id=" + id + 68 | ", firstName='" + firstName + '\'' + 69 | ", lastName='" + lastName + '\'' + 70 | '}'; 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /src/test/java/org/exampledriven/springboottestingworkshop/service/PostServiceStubTestConfigurationTest.java: -------------------------------------------------------------------------------- 1 | package org.exampledriven.springboottestingworkshop.service; 2 | 3 | import org.exampledriven.springboottestingworkshop.client.PostClient; 4 | import org.exampledriven.springboottestingworkshop.domain.PersonAndPost; 5 | import org.exampledriven.springboottestingworkshop.domain.Post; 6 | import org.junit.Test; 7 | import org.junit.runner.RunWith; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.boot.test.context.SpringBootTest; 10 | import org.springframework.boot.test.context.TestConfiguration; 11 | import org.springframework.boot.web.client.RestTemplateBuilder; 12 | import org.springframework.context.annotation.Bean; 13 | import org.springframework.test.context.junit4.SpringRunner; 14 | 15 | import java.util.LinkedList; 16 | import java.util.List; 17 | 18 | import static org.junit.Assert.assertEquals; 19 | 20 | /** 21 | * Created by Peter Szanto on 7/3/2017. 22 | */ 23 | 24 | //@RunWith(SpringRunner.class) 25 | //@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE) 26 | public class PostServiceStubTestConfigurationTest { 27 | 28 | private static final String STUBBED_TITLE = "stubbed"; 29 | private static final String JOHN = "John"; 30 | private static final String DOE = "Doe"; 31 | 32 | @Autowired 33 | private PostService postService; 34 | 35 | //@Test 36 | public void readPersonAndPost() { 37 | 38 | PersonAndPost actual = postService.readPersonAndPost(JOHN, DOE); 39 | 40 | assertEquals(JOHN, actual.getPerson().getFirstName()); 41 | assertEquals(DOE, actual.getPerson().getLastName()); 42 | 43 | assertEquals(1, actual.getPosts().size()); 44 | 45 | Post firstPost = actual.getPosts().get(0); 46 | assertEquals(STUBBED_TITLE, firstPost.getTitle()); 47 | assertEquals(100, firstPost.getId()); 48 | 49 | } 50 | 51 | //TODO 4 stub PostClient using @TestConfiguration 52 | 53 | } -------------------------------------------------------------------------------- /src/test/java/org/exampledriven/springboottestingworkshop/performance/FullContextTest.java: -------------------------------------------------------------------------------- 1 | package org.exampledriven.springboottestingworkshop.performance; 2 | 3 | import org.exampledriven.springboottestingworkshop.service.PostService; 4 | import org.exampledriven.springboottestingworkshop.performance.runner.SpringRunnerMeasurer; 5 | import org.exampledriven.springboottestingworkshop.solution.performance.ConfigInnerContextTest; 6 | import org.junit.Test; 7 | import org.junit.runner.RunWith; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.boot.test.context.SpringBootTest; 10 | import org.springframework.context.ApplicationContext; 11 | import org.springframework.context.annotation.Configuration; 12 | 13 | import static org.junit.Assert.assertEquals; 14 | import static org.junit.Assert.assertNotNull; 15 | 16 | /** 17 | * Created by Peter Szanto on 7/3/2017. 18 | */ 19 | 20 | @RunWith(SpringRunnerMeasurer.class) 21 | @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) 22 | //@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK) 23 | //@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE) 24 | //@SpringBootTest(classes = {FullContextTest.Config.class, PostService.class}) 25 | public class FullContextTest { 26 | 27 | @Autowired 28 | private ApplicationContext context; 29 | 30 | @Autowired 31 | private PostService postService; 32 | 33 | @Test 34 | public void testBeans() { 35 | 36 | // TODO 11 try the three different webenvironment options, and limiting the scope by using a nested @Configuration 37 | // Make the nested configuration work by using @MockBean instances of missing classes 38 | 39 | assertNotNull(postService); 40 | System.out.println("\n-------\nNumber of beans created : " + context.getBeanDefinitionCount()); 41 | 42 | } 43 | 44 | //nested @Configuration replaces the application’s primary configuration 45 | //@Configuration 46 | static class Config { 47 | 48 | } 49 | 50 | } -------------------------------------------------------------------------------- /src/test/java/org/exampledriven/springboottestingworkshop/solution/client/PostClientMockTest.java: -------------------------------------------------------------------------------- 1 | package org.exampledriven.springboottestingworkshop.solution.client; 2 | 3 | import org.exampledriven.springboottestingworkshop.client.PostClient; 4 | import org.exampledriven.springboottestingworkshop.domain.Post; 5 | import org.exampledriven.springboottestingworkshop.solution.TestUtil; 6 | import org.junit.Test; 7 | import org.junit.runner.RunWith; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.beans.factory.annotation.Value; 10 | import org.springframework.boot.test.autoconfigure.web.client.RestClientTest; 11 | import org.springframework.core.io.Resource; 12 | import org.springframework.http.MediaType; 13 | import org.springframework.test.context.junit4.SpringRunner; 14 | import org.springframework.test.web.client.MockRestServiceServer; 15 | 16 | import java.util.List; 17 | 18 | import static org.junit.Assert.assertEquals; 19 | import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo; 20 | import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess; 21 | 22 | /** 23 | * Created by Peter Szanto on 7/2/2017. 24 | */ 25 | @RunWith(SpringRunner.class) 26 | @RestClientTest(PostClient.class) 27 | public class PostClientMockTest { 28 | 29 | @Autowired 30 | private PostClient postClient; 31 | 32 | @Autowired 33 | private MockRestServiceServer mockRestServiceServer; 34 | 35 | @Value("posts.json") 36 | private Resource postsJson; 37 | 38 | @Test 39 | public void readPosts() throws Exception { 40 | 41 | String mockJsonResponse = TestUtil.toString(postsJson.getInputStream()); 42 | 43 | mockRestServiceServer.expect(requestTo("https://jsonplaceholder.typicode.com/posts?userId=1")) 44 | .andRespond(withSuccess(mockJsonResponse, MediaType.APPLICATION_JSON_UTF8)); 45 | 46 | List posts = postClient.readPosts(1); 47 | assertEquals(9, posts.size()); 48 | mockRestServiceServer.verify(); 49 | } 50 | 51 | } -------------------------------------------------------------------------------- /src/test/java/org/exampledriven/springboottestingworkshop/service/PostServiceStubTestComponentTest.java: -------------------------------------------------------------------------------- 1 | package org.exampledriven.springboottestingworkshop.service; 2 | 3 | import org.exampledriven.springboottestingworkshop.SpringBootTestingWorkshopApplication; 4 | import org.exampledriven.springboottestingworkshop.client.PostClient; 5 | import org.exampledriven.springboottestingworkshop.domain.PersonAndPost; 6 | import org.exampledriven.springboottestingworkshop.domain.Post; 7 | import org.junit.Test; 8 | import org.junit.runner.RunWith; 9 | import org.springframework.beans.factory.annotation.Autowired; 10 | import org.springframework.boot.test.context.SpringBootTest; 11 | import org.springframework.boot.test.context.TestComponent; 12 | import org.springframework.boot.web.client.RestTemplateBuilder; 13 | import org.springframework.context.annotation.Primary; 14 | import org.springframework.test.context.junit4.SpringRunner; 15 | 16 | import java.util.LinkedList; 17 | import java.util.List; 18 | 19 | import static org.junit.Assert.assertEquals; 20 | 21 | /** 22 | * Created by Peter Szanto on 7/3/2017. 23 | */ 24 | 25 | //@RunWith(SpringRunner.class) 26 | //@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE, 27 | // classes = {PostServiceStubTestComponentTest.PostClientStub.class, SpringBootTestingWorkshopApplication.class}) 28 | public class PostServiceStubTestComponentTest { 29 | 30 | private static final String STUBBED_TITLE = "stubbed2"; 31 | private static final String JOHN = "John"; 32 | private static final String DOE = "Doe"; 33 | 34 | @Autowired 35 | private PostService postService; 36 | 37 | //@Test 38 | public void readPersonAndPost() { 39 | 40 | PersonAndPost actual = postService.readPersonAndPost(JOHN, DOE); 41 | 42 | assertEquals(JOHN, actual.getPerson().getFirstName()); 43 | assertEquals(DOE, actual.getPerson().getLastName()); 44 | 45 | assertEquals(1, actual.getPosts().size()); 46 | 47 | Post firstPost = actual.getPosts().get(0); 48 | assertEquals(STUBBED_TITLE, firstPost.getTitle()); 49 | assertEquals(100, firstPost.getId()); 50 | 51 | } 52 | 53 | //TODO 5 stub PostClient using @TestComponent 54 | 55 | } -------------------------------------------------------------------------------- /src/test/java/org/exampledriven/springboottestingworkshop/solution/service/PostServiceCacheTest.java: -------------------------------------------------------------------------------- 1 | package org.exampledriven.springboottestingworkshop.solution.service; 2 | 3 | import org.exampledriven.springboottestingworkshop.client.PostClient; 4 | import org.exampledriven.springboottestingworkshop.domain.PersonAndPost; 5 | import org.exampledriven.springboottestingworkshop.service.PostService; 6 | import org.junit.Before; 7 | import org.junit.Test; 8 | import org.junit.runner.RunWith; 9 | import org.springframework.beans.factory.annotation.Autowired; 10 | import org.springframework.boot.test.context.SpringBootTest; 11 | import org.springframework.boot.test.mock.mockito.SpyBean; 12 | import org.springframework.cache.CacheManager; 13 | import org.springframework.test.context.junit4.SpringRunner; 14 | 15 | import static org.junit.Assert.assertEquals; 16 | import static org.mockito.Mockito.times; 17 | import static org.mockito.Mockito.verify; 18 | 19 | /** 20 | * Created by Peter Szanto on 7/3/2017. 21 | */ 22 | 23 | @RunWith(SpringRunner.class) 24 | @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE) 25 | public class PostServiceCacheTest { 26 | 27 | private static final String JOHN = "John"; 28 | private static final String DOE = "Doe"; 29 | 30 | @Autowired 31 | private PostService postService; 32 | 33 | @SpyBean 34 | private PostClient postClient; 35 | 36 | @Autowired 37 | private CacheManager cacheManager; 38 | 39 | @Before 40 | public void evictAllCaches() { 41 | cacheManager.getCacheNames().parallelStream().forEach(name -> cacheManager.getCache(name).clear()); 42 | } 43 | 44 | @Test 45 | public void readPersonAndPost() { 46 | 47 | PersonAndPost personFromDB = postService.readPersonAndPost(JOHN, DOE); 48 | 49 | assertEquals(JOHN, personFromDB.getPerson().getFirstName()); 50 | assertEquals(DOE, personFromDB.getPerson().getLastName()); 51 | 52 | assertEquals(10, personFromDB.getPosts().size()); 53 | 54 | PersonAndPost personCached = postService.readPersonAndPost(JOHN, DOE); 55 | 56 | assertEquals(JOHN, personCached.getPerson().getFirstName()); 57 | assertEquals(DOE, personCached.getPerson().getLastName()); 58 | 59 | verify(postClient, times(1)).readPosts(1); 60 | 61 | } 62 | 63 | } -------------------------------------------------------------------------------- /src/test/java/org/exampledriven/springboottestingworkshop/solution/controller/PostControllerRandomPortTest.java: -------------------------------------------------------------------------------- 1 | package org.exampledriven.springboottestingworkshop.solution.controller; 2 | 3 | import org.exampledriven.springboottestingworkshop.domain.PersonAndPost; 4 | import org.exampledriven.springboottestingworkshop.domain.Post; 5 | import org.junit.Test; 6 | import org.junit.runner.RunWith; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; 9 | import org.springframework.boot.test.context.SpringBootTest; 10 | import org.springframework.boot.test.web.client.TestRestTemplate; 11 | import org.springframework.http.MediaType; 12 | import org.springframework.test.context.junit4.SpringRunner; 13 | import org.springframework.test.web.servlet.MockMvc; 14 | import org.springframework.test.web.servlet.ResultActions; 15 | 16 | import static org.hamcrest.Matchers.any; 17 | import static org.hamcrest.Matchers.is; 18 | import static org.hamcrest.collection.IsCollectionWithSize.hasSize; 19 | import static org.junit.Assert.assertEquals; 20 | import static org.junit.Assert.assertTrue; 21 | import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; 22 | import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; 23 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; 24 | 25 | /** 26 | * Created by Peter Szanto on 7/4/2017. 27 | */ 28 | 29 | @RunWith(SpringRunner.class) 30 | @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) 31 | public class PostControllerRandomPortTest { 32 | private static final String JOHN = "John"; 33 | private static final String DOE = "Doe"; 34 | private static final int USER_ID = 1; 35 | 36 | @Autowired 37 | private TestRestTemplate testRestTemplate; 38 | 39 | @Test 40 | public void readPost() { 41 | 42 | PersonAndPost personAndPost = testRestTemplate.getForObject("/post?firstName={firstName}&lastName={lastName}", PersonAndPost.class, JOHN, DOE); 43 | 44 | assertEquals(JOHN, personAndPost.getPerson().getFirstName()); 45 | assertEquals(DOE, personAndPost.getPerson().getLastName()); 46 | assertEquals(USER_ID, personAndPost.getPerson().getId()); 47 | 48 | assertEquals(10, personAndPost.getPosts().size()); 49 | 50 | Post firstPost = personAndPost.getPosts().get(0); 51 | assertEquals(1, firstPost.getId()); 52 | assertEquals(USER_ID, firstPost.getUserId()); 53 | assertTrue(firstPost.getTitle() != null); 54 | assertTrue(firstPost.getBody() != null); 55 | 56 | } 57 | 58 | } -------------------------------------------------------------------------------- /src/test/resources/posts.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "userId": 1, 4 | "id": 1, 5 | "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit", 6 | "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto" 7 | }, 8 | { 9 | "userId": 1, 10 | "id": 2, 11 | "title": "qui est esse", 12 | "body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla" 13 | }, 14 | { 15 | "userId": 1, 16 | "id": 3, 17 | "title": "ea molestias quasi exercitationem repellat qui ipsa sit aut", 18 | "body": "et iusto sed quo iure\nvoluptatem occaecati omnis eligendi aut ad\nvoluptatem doloribus vel accusantium quis pariatur\nmolestiae porro eius odio et labore et velit aut" 19 | }, 20 | { 21 | "userId": 1, 22 | "id": 4, 23 | "title": "eum et est occaecati", 24 | "body": "ullam et saepe reiciendis voluptatem adipisci\nsit amet autem assumenda provident rerum culpa\nquis hic commodi nesciunt rem tenetur doloremque ipsam iure\nquis sunt voluptatem rerum illo velit" 25 | }, 26 | { 27 | "userId": 1, 28 | "id": 5, 29 | "title": "nesciunt quas odio", 30 | "body": "repudiandae veniam quaerat sunt sed\nalias aut fugiat sit autem sed est\nvoluptatem omnis possimus esse voluptatibus quis\nest aut tenetur dolor neque" 31 | }, 32 | { 33 | "userId": 1, 34 | "id": 6, 35 | "title": "dolorem eum magni eos aperiam quia", 36 | "body": "ut aspernatur corporis harum nihil quis provident sequi\nmollitia nobis aliquid molestiae\nperspiciatis et ea nemo ab reprehenderit accusantium quas\nvoluptate dolores velit et doloremque molestiae" 37 | }, 38 | { 39 | "userId": 1, 40 | "id": 7, 41 | "title": "magnam facilis autem", 42 | "body": "dolore placeat quibusdam ea quo vitae\nmagni quis enim qui quis quo nemo aut saepe\nquidem repellat excepturi ut quia\nsunt ut sequi eos ea sed quas" 43 | }, 44 | { 45 | "userId": 1, 46 | "id": 8, 47 | "title": "dolorem dolore est ipsam", 48 | "body": "dignissimos aperiam dolorem qui eum\nfacilis quibusdam animi sint suscipit qui sint possimus cum\nquaerat magni maiores excepturi\nipsam ut commodi dolor voluptatum modi aut vitae" 49 | }, 50 | { 51 | "userId": 1, 52 | "id": 9, 53 | "title": "nesciunt iure omnis dolorem tempora et accusantium", 54 | "body": "consectetur animi nesciunt iure dolore\nenim quia ad\nveniam autem ut quam aut nobis\net est aut quod aut provident voluptas autem voluptas" 55 | } 56 | ] -------------------------------------------------------------------------------- /src/test/java/org/exampledriven/springboottestingworkshop/solution/controller/PostControllerMockTest.java: -------------------------------------------------------------------------------- 1 | package org.exampledriven.springboottestingworkshop.solution.controller; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; 7 | import org.springframework.boot.test.context.SpringBootTest; 8 | import org.springframework.http.MediaType; 9 | import org.springframework.test.context.junit4.SpringRunner; 10 | import org.springframework.test.web.servlet.MockMvc; 11 | import org.springframework.test.web.servlet.ResultActions; 12 | 13 | import static org.hamcrest.Matchers.any; 14 | import static org.hamcrest.Matchers.is; 15 | import static org.hamcrest.collection.IsCollectionWithSize.hasSize; 16 | import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; 17 | import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; 18 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; 19 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; 20 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; 21 | 22 | /** 23 | * Created by Peter Szanto on 7/4/2017. 24 | */ 25 | 26 | @RunWith(SpringRunner.class) 27 | @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK) 28 | @AutoConfigureMockMvc 29 | public class PostControllerMockTest { 30 | private static final String JOHN = "John"; 31 | private static final String DOE = "Doe"; 32 | 33 | @Autowired 34 | private MockMvc mockMvc; 35 | 36 | @Test 37 | public void readPost() throws Exception { 38 | 39 | ResultActions resultActions = mockMvc.perform( 40 | get("/post") 41 | .param("firstName", JOHN) 42 | .param("lastName", DOE) 43 | ); 44 | 45 | resultActions 46 | .andDo(print()) 47 | .andExpect(status().isOk()) 48 | .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)); 49 | 50 | resultActions 51 | .andExpect(jsonPath("$.person.id", is(1))) 52 | .andExpect(jsonPath("$.person.lastName", is(DOE))) 53 | .andExpect(jsonPath("$.person.firstName", is(JOHN))); 54 | 55 | resultActions 56 | .andExpect(jsonPath("$.posts", hasSize(10))) 57 | .andExpect(jsonPath("$.posts[0].userId", is(1))) 58 | .andExpect(jsonPath("$.posts[0].title", any(String.class))) 59 | .andExpect(jsonPath("$.posts[0].body", any(String.class))); 60 | 61 | } 62 | 63 | } -------------------------------------------------------------------------------- /src/test/java/org/exampledriven/springboottestingworkshop/solution/service/PostServiceStubTestConfigurationTest.java: -------------------------------------------------------------------------------- 1 | package org.exampledriven.springboottestingworkshop.solution.service; 2 | 3 | import org.exampledriven.springboottestingworkshop.client.PostClient; 4 | import org.exampledriven.springboottestingworkshop.domain.PersonAndPost; 5 | import org.exampledriven.springboottestingworkshop.domain.Post; 6 | import org.exampledriven.springboottestingworkshop.service.PostService; 7 | import org.springframework.boot.test.context.TestConfiguration; 8 | import org.springframework.boot.web.client.RestTemplateBuilder; 9 | import org.junit.Test; 10 | import org.junit.runner.RunWith; 11 | import org.springframework.beans.factory.annotation.Autowired; 12 | import org.springframework.boot.test.context.SpringBootTest; 13 | import org.springframework.context.annotation.Bean; 14 | import org.springframework.test.context.junit4.SpringRunner; 15 | 16 | import java.util.LinkedList; 17 | import java.util.List; 18 | 19 | import static org.junit.Assert.assertEquals; 20 | 21 | /** 22 | * Created by Peter Szanto on 7/3/2017. 23 | */ 24 | 25 | @RunWith(SpringRunner.class) 26 | @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE) 27 | public class PostServiceStubTestConfigurationTest { 28 | 29 | private static final String STUBBED_TITLE = "stubbed"; 30 | private static final String JOHN = "John"; 31 | private static final String DOE = "Doe"; 32 | 33 | @Autowired 34 | private PostService postService; 35 | 36 | @Test 37 | public void readPersonAndPost() { 38 | 39 | PersonAndPost actual = postService.readPersonAndPost(JOHN, DOE); 40 | 41 | assertEquals(JOHN, actual.getPerson().getFirstName()); 42 | assertEquals(DOE, actual.getPerson().getLastName()); 43 | 44 | assertEquals(1, actual.getPosts().size()); 45 | 46 | Post firstPost = actual.getPosts().get(0); 47 | assertEquals(STUBBED_TITLE, firstPost.getTitle()); 48 | assertEquals(100, firstPost.getId()); 49 | 50 | } 51 | 52 | @TestConfiguration 53 | public static class NestedConfig { 54 | 55 | @Bean 56 | public PostClient postClient() { 57 | return new PostClient(new RestTemplateBuilder()) { 58 | 59 | @Override 60 | public List readPosts(int userId) { 61 | 62 | List stubResponse = new LinkedList<>(); 63 | 64 | Post post = new Post(); 65 | post.setId(100); 66 | post.setTitle(STUBBED_TITLE); 67 | 68 | stubResponse.add(post); 69 | 70 | return stubResponse; 71 | } 72 | }; 73 | } 74 | 75 | } 76 | 77 | } -------------------------------------------------------------------------------- /src/test/java/org/exampledriven/springboottestingworkshop/solution/service/PostServiceStubTestComponentTest.java: -------------------------------------------------------------------------------- 1 | package org.exampledriven.springboottestingworkshop.solution.service; 2 | 3 | import org.exampledriven.springboottestingworkshop.SpringBootTestingWorkshopApplication; 4 | import org.exampledriven.springboottestingworkshop.client.PostClient; 5 | import org.exampledriven.springboottestingworkshop.domain.PersonAndPost; 6 | import org.exampledriven.springboottestingworkshop.domain.Post; 7 | import org.exampledriven.springboottestingworkshop.service.PostService; 8 | import org.junit.Test; 9 | import org.junit.runner.RunWith; 10 | import org.springframework.beans.factory.annotation.Autowired; 11 | import org.springframework.boot.test.context.SpringBootTest; 12 | import org.springframework.boot.test.context.TestComponent; 13 | import org.springframework.boot.web.client.RestTemplateBuilder; 14 | import org.springframework.context.annotation.Primary; 15 | import org.springframework.test.context.junit4.SpringRunner; 16 | 17 | import java.util.LinkedList; 18 | import java.util.List; 19 | 20 | import static org.junit.Assert.assertEquals; 21 | 22 | /** 23 | * Created by Peter Szanto on 7/3/2017. 24 | */ 25 | 26 | @RunWith(SpringRunner.class) 27 | @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE, 28 | classes = {PostServiceStubTestComponentTest.PostClientStub.class, SpringBootTestingWorkshopApplication.class}) 29 | public class PostServiceStubTestComponentTest { 30 | 31 | private static final String STUBBED_TITLE = "stubbed2"; 32 | private static final String JOHN = "John"; 33 | private static final String DOE = "Doe"; 34 | 35 | @Autowired 36 | private PostService postService; 37 | 38 | @Test 39 | public void readPersonAndPost() { 40 | 41 | PersonAndPost actual = postService.readPersonAndPost(JOHN, DOE); 42 | 43 | assertEquals(JOHN, actual.getPerson().getFirstName()); 44 | assertEquals(DOE, actual.getPerson().getLastName()); 45 | 46 | assertEquals(1, actual.getPosts().size()); 47 | 48 | Post firstPost = actual.getPosts().get(0); 49 | assertEquals(STUBBED_TITLE, firstPost.getTitle()); 50 | assertEquals(100, firstPost.getId()); 51 | 52 | } 53 | 54 | @TestComponent 55 | @Primary 56 | public static class PostClientStub extends PostClient { 57 | 58 | public PostClientStub(RestTemplateBuilder restTemplateBuilder) { 59 | super(restTemplateBuilder); 60 | } 61 | 62 | @Override 63 | public List readPosts(int userId) { 64 | List stubResponse = new LinkedList<>(); 65 | Post post = new Post(); 66 | post.setId(100); 67 | post.setTitle(STUBBED_TITLE); 68 | 69 | stubResponse.add(post); 70 | 71 | return stubResponse; 72 | } 73 | } 74 | } -------------------------------------------------------------------------------- /src/test/java/org/exampledriven/springboottestingworkshop/solution/service/PostServiceMockTest.java: -------------------------------------------------------------------------------- 1 | package org.exampledriven.springboottestingworkshop.solution.service; 2 | 3 | import org.exampledriven.springboottestingworkshop.client.PostClient; 4 | import org.exampledriven.springboottestingworkshop.domain.Person; 5 | import org.exampledriven.springboottestingworkshop.domain.PersonAndPost; 6 | import org.exampledriven.springboottestingworkshop.domain.Post; 7 | import org.exampledriven.springboottestingworkshop.repository.PersonRepository; 8 | import org.exampledriven.springboottestingworkshop.service.PostService; 9 | import org.junit.Test; 10 | import org.junit.runner.RunWith; 11 | import org.springframework.beans.factory.annotation.Autowired; 12 | import org.springframework.boot.test.context.SpringBootTest; 13 | import org.springframework.boot.test.mock.mockito.MockBean; 14 | import org.springframework.test.context.junit4.SpringRunner; 15 | 16 | import java.util.LinkedList; 17 | import java.util.List; 18 | 19 | import static org.junit.Assert.assertEquals; 20 | import static org.mockito.BDDMockito.given; 21 | import static org.mockito.Mockito.verify; 22 | 23 | /** 24 | * Created by Peter Szanto on 7/3/2017. 25 | */ 26 | 27 | @RunWith(SpringRunner.class) 28 | @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE) 29 | public class PostServiceMockTest { 30 | 31 | @Autowired 32 | private PostService postService; 33 | 34 | @MockBean 35 | private PostClient postClient; 36 | 37 | @MockBean 38 | private PersonRepository personRepository; 39 | 40 | @Test 41 | public void readPersonAndPost() { 42 | 43 | // setup postClient 44 | Person expectedPerson = new Person(); 45 | expectedPerson.setFirstName("Ada"); 46 | expectedPerson.setLastName("Lovelace"); 47 | expectedPerson.setId(1); 48 | 49 | List expectedPosts = new LinkedList<>(); 50 | Post post = new Post(); 51 | post.setId(6); 52 | expectedPosts.add(post); 53 | 54 | given(postClient.readPosts(1)).willReturn(expectedPosts); 55 | 56 | // setup personRepository 57 | given(personRepository.findByFirstNameAndLastName(expectedPerson.getFirstName(), expectedPerson.getLastName())).willReturn(expectedPerson); 58 | 59 | 60 | // perform 61 | PersonAndPost actual = postService.readPersonAndPost(expectedPerson.getFirstName(), expectedPerson.getLastName()); 62 | 63 | assertEquals(expectedPerson.getFirstName(), actual.getPerson().getFirstName()); 64 | assertEquals(expectedPerson.getLastName(), actual.getPerson().getLastName()); 65 | 66 | assertEquals(1, actual.getPosts().size()); 67 | 68 | verify(postClient).readPosts(1); 69 | verify(personRepository).findByFirstNameAndLastName(expectedPerson.getFirstName(), expectedPerson.getLastName()); 70 | 71 | } 72 | 73 | } -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | org.exampledriven 7 | spring-boot-testing-workshop 8 | 0.0.1-SNAPSHOT 9 | jar 10 | 11 | spring-boot-testing-workshop 12 | Demo project for Spring Boot 13 | 14 | 15 | org.springframework.boot 16 | spring-boot-starter-parent 17 | 1.5.12.RELEASE 18 | 19 | 20 | 21 | 22 | UTF-8 23 | UTF-8 24 | 1.8 25 | 26 | 27 | 28 | 29 | org.springframework.boot 30 | spring-boot-starter-web 31 | 32 | 33 | 34 | org.springframework.boot 35 | spring-boot-starter-data-jpa 36 | 37 | 38 | 39 | 40 | 41 | org.springframework.boot 42 | spring-boot-starter-cache 43 | 44 | 45 | javax.cache 46 | cache-api 47 | 48 | 49 | org.ehcache 50 | ehcache 51 | 52 | 53 | 54 | 55 | org.springframework.boot 56 | spring-boot-devtools 57 | runtime 58 | 59 | 60 | com.h2database 61 | h2 62 | runtime 63 | 64 | 65 | org.springframework.boot 66 | spring-boot-starter-test 67 | test 68 | 69 | 70 | 71 | 72 | 73 | 74 | org.springframework.boot 75 | spring-boot-maven-plugin 76 | 77 | 78 | 79 | 80 | 81 | 82 | -------------------------------------------------------------------------------- /mvnw.cmd: -------------------------------------------------------------------------------- 1 | @REM ---------------------------------------------------------------------------- 2 | @REM Licensed to the Apache Software Foundation (ASF) under one 3 | @REM or more contributor license agreements. See the NOTICE file 4 | @REM distributed with this work for additional information 5 | @REM regarding copyright ownership. The ASF licenses this file 6 | @REM to you under the Apache License, Version 2.0 (the 7 | @REM "License"); you may not use this file except in compliance 8 | @REM with the License. You may obtain a copy of the License at 9 | @REM 10 | @REM http://www.apache.org/licenses/LICENSE-2.0 11 | @REM 12 | @REM Unless required by applicable law or agreed to in writing, 13 | @REM software distributed under the License is distributed on an 14 | @REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | @REM KIND, either express or implied. See the License for the 16 | @REM specific language governing permissions and limitations 17 | @REM under the License. 18 | @REM ---------------------------------------------------------------------------- 19 | 20 | @REM ---------------------------------------------------------------------------- 21 | @REM Maven2 Start Up Batch script 22 | @REM 23 | @REM Required ENV vars: 24 | @REM JAVA_HOME - location of a JDK home dir 25 | @REM 26 | @REM Optional ENV vars 27 | @REM M2_HOME - location of maven2's installed home dir 28 | @REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands 29 | @REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending 30 | @REM MAVEN_OPTS - parameters passed to the Java VM when running Maven 31 | @REM e.g. to debug Maven itself, use 32 | @REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 33 | @REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files 34 | @REM ---------------------------------------------------------------------------- 35 | 36 | @REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' 37 | @echo off 38 | @REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' 39 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% 40 | 41 | @REM set %HOME% to equivalent of $HOME 42 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") 43 | 44 | @REM Execute a user defined script before this one 45 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre 46 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending 47 | if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" 48 | if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" 49 | :skipRcPre 50 | 51 | @setlocal 52 | 53 | set ERROR_CODE=0 54 | 55 | @REM To isolate internal variables from possible post scripts, we use another setlocal 56 | @setlocal 57 | 58 | @REM ==== START VALIDATION ==== 59 | if not "%JAVA_HOME%" == "" goto OkJHome 60 | 61 | echo. 62 | echo Error: JAVA_HOME not found in your environment. >&2 63 | echo Please set the JAVA_HOME variable in your environment to match the >&2 64 | echo location of your Java installation. >&2 65 | echo. 66 | goto error 67 | 68 | :OkJHome 69 | if exist "%JAVA_HOME%\bin\java.exe" goto init 70 | 71 | echo. 72 | echo Error: JAVA_HOME is set to an invalid directory. >&2 73 | echo JAVA_HOME = "%JAVA_HOME%" >&2 74 | echo Please set the JAVA_HOME variable in your environment to match the >&2 75 | echo location of your Java installation. >&2 76 | echo. 77 | goto error 78 | 79 | @REM ==== END VALIDATION ==== 80 | 81 | :init 82 | 83 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn". 84 | @REM Fallback to current working directory if not found. 85 | 86 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% 87 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir 88 | 89 | set EXEC_DIR=%CD% 90 | set WDIR=%EXEC_DIR% 91 | :findBaseDir 92 | IF EXIST "%WDIR%"\.mvn goto baseDirFound 93 | cd .. 94 | IF "%WDIR%"=="%CD%" goto baseDirNotFound 95 | set WDIR=%CD% 96 | goto findBaseDir 97 | 98 | :baseDirFound 99 | set MAVEN_PROJECTBASEDIR=%WDIR% 100 | cd "%EXEC_DIR%" 101 | goto endDetectBaseDir 102 | 103 | :baseDirNotFound 104 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR% 105 | cd "%EXEC_DIR%" 106 | 107 | :endDetectBaseDir 108 | 109 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig 110 | 111 | @setlocal EnableExtensions EnableDelayedExpansion 112 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a 113 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% 114 | 115 | :endReadAdditionalConfig 116 | 117 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" 118 | 119 | set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" 120 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 121 | 122 | %MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* 123 | if ERRORLEVEL 1 goto error 124 | goto end 125 | 126 | :error 127 | set ERROR_CODE=1 128 | 129 | :end 130 | @endlocal & set ERROR_CODE=%ERROR_CODE% 131 | 132 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost 133 | @REM check for post script, once with legacy .bat ending and once with .cmd ending 134 | if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" 135 | if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" 136 | :skipRcPost 137 | 138 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' 139 | if "%MAVEN_BATCH_PAUSE%" == "on" pause 140 | 141 | if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% 142 | 143 | exit /B %ERROR_CODE% 144 | -------------------------------------------------------------------------------- /mvnw: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # ---------------------------------------------------------------------------- 3 | # Licensed to the Apache Software Foundation (ASF) under one 4 | # or more contributor license agreements. See the NOTICE file 5 | # distributed with this work for additional information 6 | # regarding copyright ownership. The ASF licenses this file 7 | # to you under the Apache License, Version 2.0 (the 8 | # "License"); you may not use this file except in compliance 9 | # with the License. You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, 14 | # software distributed under the License is distributed on an 15 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | # KIND, either express or implied. See the License for the 17 | # specific language governing permissions and limitations 18 | # under the License. 19 | # ---------------------------------------------------------------------------- 20 | 21 | # ---------------------------------------------------------------------------- 22 | # Maven2 Start Up Batch script 23 | # 24 | # Required ENV vars: 25 | # ------------------ 26 | # JAVA_HOME - location of a JDK home dir 27 | # 28 | # Optional ENV vars 29 | # ----------------- 30 | # M2_HOME - location of maven2's installed home dir 31 | # MAVEN_OPTS - parameters passed to the Java VM when running Maven 32 | # e.g. to debug Maven itself, use 33 | # set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 34 | # MAVEN_SKIP_RC - flag to disable loading of mavenrc files 35 | # ---------------------------------------------------------------------------- 36 | 37 | if [ -z "$MAVEN_SKIP_RC" ] ; then 38 | 39 | if [ -f /etc/mavenrc ] ; then 40 | . /etc/mavenrc 41 | fi 42 | 43 | if [ -f "$HOME/.mavenrc" ] ; then 44 | . "$HOME/.mavenrc" 45 | fi 46 | 47 | fi 48 | 49 | # OS specific support. $var _must_ be set to either true or false. 50 | cygwin=false; 51 | darwin=false; 52 | mingw=false 53 | case "`uname`" in 54 | CYGWIN*) cygwin=true ;; 55 | MINGW*) mingw=true;; 56 | Darwin*) darwin=true 57 | # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home 58 | # See https://developer.apple.com/library/mac/qa/qa1170/_index.html 59 | if [ -z "$JAVA_HOME" ]; then 60 | if [ -x "/usr/libexec/java_home" ]; then 61 | export JAVA_HOME="`/usr/libexec/java_home`" 62 | else 63 | export JAVA_HOME="/Library/Java/Home" 64 | fi 65 | fi 66 | ;; 67 | esac 68 | 69 | if [ -z "$JAVA_HOME" ] ; then 70 | if [ -r /etc/gentoo-release ] ; then 71 | JAVA_HOME=`java-config --jre-home` 72 | fi 73 | fi 74 | 75 | if [ -z "$M2_HOME" ] ; then 76 | ## resolve links - $0 may be a link to maven's home 77 | PRG="$0" 78 | 79 | # need this for relative symlinks 80 | while [ -h "$PRG" ] ; do 81 | ls=`ls -ld "$PRG"` 82 | link=`expr "$ls" : '.*-> \(.*\)$'` 83 | if expr "$link" : '/.*' > /dev/null; then 84 | PRG="$link" 85 | else 86 | PRG="`dirname "$PRG"`/$link" 87 | fi 88 | done 89 | 90 | saveddir=`pwd` 91 | 92 | M2_HOME=`dirname "$PRG"`/.. 93 | 94 | # make it fully qualified 95 | M2_HOME=`cd "$M2_HOME" && pwd` 96 | 97 | cd "$saveddir" 98 | # echo Using m2 at $M2_HOME 99 | fi 100 | 101 | # For Cygwin, ensure paths are in UNIX format before anything is touched 102 | if $cygwin ; then 103 | [ -n "$M2_HOME" ] && 104 | M2_HOME=`cygpath --unix "$M2_HOME"` 105 | [ -n "$JAVA_HOME" ] && 106 | JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 107 | [ -n "$CLASSPATH" ] && 108 | CLASSPATH=`cygpath --path --unix "$CLASSPATH"` 109 | fi 110 | 111 | # For Migwn, ensure paths are in UNIX format before anything is touched 112 | if $mingw ; then 113 | [ -n "$M2_HOME" ] && 114 | M2_HOME="`(cd "$M2_HOME"; pwd)`" 115 | [ -n "$JAVA_HOME" ] && 116 | JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" 117 | # TODO classpath? 118 | fi 119 | 120 | if [ -z "$JAVA_HOME" ]; then 121 | javaExecutable="`which javac`" 122 | if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then 123 | # readlink(1) is not available as standard on Solaris 10. 124 | readLink=`which readlink` 125 | if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then 126 | if $darwin ; then 127 | javaHome="`dirname \"$javaExecutable\"`" 128 | javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" 129 | else 130 | javaExecutable="`readlink -f \"$javaExecutable\"`" 131 | fi 132 | javaHome="`dirname \"$javaExecutable\"`" 133 | javaHome=`expr "$javaHome" : '\(.*\)/bin'` 134 | JAVA_HOME="$javaHome" 135 | export JAVA_HOME 136 | fi 137 | fi 138 | fi 139 | 140 | if [ -z "$JAVACMD" ] ; then 141 | if [ -n "$JAVA_HOME" ] ; then 142 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 143 | # IBM's JDK on AIX uses strange locations for the executables 144 | JAVACMD="$JAVA_HOME/jre/sh/java" 145 | else 146 | JAVACMD="$JAVA_HOME/bin/java" 147 | fi 148 | else 149 | JAVACMD="`which java`" 150 | fi 151 | fi 152 | 153 | if [ ! -x "$JAVACMD" ] ; then 154 | echo "Error: JAVA_HOME is not defined correctly." >&2 155 | echo " We cannot execute $JAVACMD" >&2 156 | exit 1 157 | fi 158 | 159 | if [ -z "$JAVA_HOME" ] ; then 160 | echo "Warning: JAVA_HOME environment variable is not set." 161 | fi 162 | 163 | CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher 164 | 165 | # traverses directory structure from process work directory to filesystem root 166 | # first directory with .mvn subdirectory is considered project base directory 167 | find_maven_basedir() { 168 | 169 | if [ -z "$1" ] 170 | then 171 | echo "Path not specified to find_maven_basedir" 172 | return 1 173 | fi 174 | 175 | basedir="$1" 176 | wdir="$1" 177 | while [ "$wdir" != '/' ] ; do 178 | if [ -d "$wdir"/.mvn ] ; then 179 | basedir=$wdir 180 | break 181 | fi 182 | # workaround for JBEAP-8937 (on Solaris 10/Sparc) 183 | if [ -d "${wdir}" ]; then 184 | wdir=`cd "$wdir/.."; pwd` 185 | fi 186 | # end of workaround 187 | done 188 | echo "${basedir}" 189 | } 190 | 191 | # concatenates all lines of a file 192 | concat_lines() { 193 | if [ -f "$1" ]; then 194 | echo "$(tr -s '\n' ' ' < "$1")" 195 | fi 196 | } 197 | 198 | BASE_DIR=`find_maven_basedir "$(pwd)"` 199 | if [ -z "$BASE_DIR" ]; then 200 | exit 1; 201 | fi 202 | 203 | export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} 204 | echo $MAVEN_PROJECTBASEDIR 205 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" 206 | 207 | # For Cygwin, switch paths to Windows format before running java 208 | if $cygwin; then 209 | [ -n "$M2_HOME" ] && 210 | M2_HOME=`cygpath --path --windows "$M2_HOME"` 211 | [ -n "$JAVA_HOME" ] && 212 | JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` 213 | [ -n "$CLASSPATH" ] && 214 | CLASSPATH=`cygpath --path --windows "$CLASSPATH"` 215 | [ -n "$MAVEN_PROJECTBASEDIR" ] && 216 | MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` 217 | fi 218 | 219 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 220 | 221 | exec "$JAVACMD" \ 222 | $MAVEN_OPTS \ 223 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ 224 | "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ 225 | ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" 226 | --------------------------------------------------------------------------------