From 3725e6060e176d03043072902b0912f7fd7d8954 Mon Sep 17 00:00:00 2001 From: "zahar.kalosha" Date: Wed, 12 Jun 2024 13:58:24 +0300 Subject: [PATCH 1/9] Refactor pom.sql and add h2 dependency --- pom.xml | 62 ++++++++++++++++++++++++++++++++++----------------------- 1 file changed, 37 insertions(+), 25 deletions(-) diff --git a/pom.xml b/pom.xml index 2c23e76..a079727 100644 --- a/pom.xml +++ b/pom.xml @@ -24,30 +24,43 @@ 11 - - - org.springframework.boot - spring-boot-starter-data-jpa - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-validation - - - org.postgresql - postgresql - runtime - - - org.springframework.boot - spring-boot-starter-test - test - - + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-validation + + + org.springframework.boot + spring-boot-starter-test + test + + + + + org.postgresql + postgresql + runtime + + + com.h2database + h2 + runtime + + + + junit + junit + test + + @@ -58,5 +71,4 @@ - From d7a806e566d5fff69d229193193aa2b4a418b35b Mon Sep 17 00:00:00 2001 From: "zahar.kalosha" Date: Thu, 13 Jun 2024 15:13:11 +0300 Subject: [PATCH 2/9] Bug: QuestionControllerTest have problem with Autowiring --- .../controller/QuestionControllerTest.java | 45 +++++++++++++++++++ src/test/resources/application.properties | 18 ++++++++ 2 files changed, 63 insertions(+) create mode 100644 src/test/java/com/example/postgresdemo/controller/QuestionControllerTest.java create mode 100644 src/test/resources/application.properties diff --git a/src/test/java/com/example/postgresdemo/controller/QuestionControllerTest.java b/src/test/java/com/example/postgresdemo/controller/QuestionControllerTest.java new file mode 100644 index 0000000..66acbe8 --- /dev/null +++ b/src/test/java/com/example/postgresdemo/controller/QuestionControllerTest.java @@ -0,0 +1,45 @@ +package com.example.postgresdemo.controller; + +import com.example.postgresdemo.model.Question; +import com.example.postgresdemo.repository.QuestionRepository; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.test.web.servlet.result.MockMvcResultMatchers; +import org.springframework.web.context.WebApplicationContext; + +import java.util.List; + +import static org.junit.Assert.assertNotNull; +import static org.mockito.Mockito.when; + +//@SpringBootTest +//@WebMvcTest +@WebMvcTest(QuestionController.class) +public class QuestionControllerTest { +// private QuestionRepository questionRepository; + + @Autowired + private WebApplicationContext webApplicationContext; + + @Autowired + private MockMvc mockMvc; + + @Test + public void testCreateMockMvc() { + assertNotNull(mockMvc); + } + + @Test + public void testGetQuestions() throws Exception { +// when(questionRepository.findAll()).thenReturn(List.of(new Question())); + + this.mockMvc + .perform(MockMvcRequestBuilders.get("/questions")) + .andExpect(MockMvcResultMatchers.status().isOk()); + } +} diff --git a/src/test/resources/application.properties b/src/test/resources/application.properties new file mode 100644 index 0000000..68e3f46 --- /dev/null +++ b/src/test/resources/application.properties @@ -0,0 +1,18 @@ +spring.datasource.url=jdbc:h2:mem:test;MODE=PostgreSQL; +spring.datasource.driver-class-name=org.h2.Driver +spring.datasource.username=${DB_USER} +spring.datasource.password=${DB_PASSWORD} +# We add the MySQL Dialect so that it understands and generates the query based on MySQL +spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect + +spring.h2.console.enabled=true +#spring.jpa.defer-datasource-initialization=true +spring.jpa.hibernate.ddl-auto=update +#spring.jpa.hibernate.naming.implicit-strategy=org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImpl +#spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl +spring.jpa.properties.hibernate.format_sql=true +#spring.jpa.hibernate.naming-strategy=org.hibernate.cfg.ImprovedNamingStrategy +spring.jpa.properties.hibernate.show_sql=true + + +spring.sql.init.mode=always From 95049a3f602bda9f4006bb66306fd6327276b353 Mon Sep 17 00:00:00 2001 From: "zahar.kalosha" Date: Thu, 13 Jun 2024 18:14:36 +0300 Subject: [PATCH 3/9] Fix pom.xml junit dependency --- pom.xml | 5 ----- 1 file changed, 5 deletions(-) diff --git a/pom.xml b/pom.xml index a079727..60941b5 100644 --- a/pom.xml +++ b/pom.xml @@ -55,11 +55,6 @@ runtime - - junit - junit - test - From 5b82e535af50ff26a0535a2a72860152d1e6fdf8 Mon Sep 17 00:00:00 2001 From: "zahar.kalosha" Date: Thu, 13 Jun 2024 18:15:29 +0300 Subject: [PATCH 4/9] Add application.properties for test directory --- src/test/resources/application.properties | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/src/test/resources/application.properties b/src/test/resources/application.properties index 68e3f46..6d94c03 100644 --- a/src/test/resources/application.properties +++ b/src/test/resources/application.properties @@ -6,13 +6,9 @@ spring.datasource.password=${DB_PASSWORD} spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect spring.h2.console.enabled=true -#spring.jpa.defer-datasource-initialization=true spring.jpa.hibernate.ddl-auto=update -#spring.jpa.hibernate.naming.implicit-strategy=org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImpl -#spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl spring.jpa.properties.hibernate.format_sql=true -#spring.jpa.hibernate.naming-strategy=org.hibernate.cfg.ImprovedNamingStrategy -spring.jpa.properties.hibernate.show_sql=true +#spring.jpa.properties.hibernate.show_sql=true spring.sql.init.mode=always From 37174b5c1ddeedd6f762394e8ff278da359f5033 Mon Sep 17 00:00:00 2001 From: "zahar.kalosha" Date: Thu, 13 Jun 2024 18:15:54 +0300 Subject: [PATCH 5/9] Add first correct test --- .../controller/QuestionControllerTest.java | 76 ++++++++++++++++--- 1 file changed, 66 insertions(+), 10 deletions(-) diff --git a/src/test/java/com/example/postgresdemo/controller/QuestionControllerTest.java b/src/test/java/com/example/postgresdemo/controller/QuestionControllerTest.java index 66acbe8..4fcbda2 100644 --- a/src/test/java/com/example/postgresdemo/controller/QuestionControllerTest.java +++ b/src/test/java/com/example/postgresdemo/controller/QuestionControllerTest.java @@ -2,44 +2,100 @@ import com.example.postgresdemo.model.Question; import com.example.postgresdemo.repository.QuestionRepository; + +import org.hamcrest.Matchers; import org.junit.jupiter.api.Test; +import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.ResultMatcher; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.web.context.WebApplicationContext; + +import java.util.Arrays; import java.util.List; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.mockito.Mockito.when; +import static org.springframework.test.web.client.match.MockRestRequestMatchers.jsonPath; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@SpringBootTest -//@SpringBootTest -//@WebMvcTest -@WebMvcTest(QuestionController.class) +@AutoConfigureMockMvc public class QuestionControllerTest { -// private QuestionRepository questionRepository; + @Autowired + private QuestionRepository questionRepository; @Autowired private WebApplicationContext webApplicationContext; @Autowired private MockMvc mockMvc; + @Autowired + private QuestionController questionController; @Test public void testCreateMockMvc() { assertNotNull(mockMvc); } + private boolean fillQuestions(Integer number) { + try { + for (int i = 0; i < number; i++) { + Question question = new Question(); + question.setTitle("Question " + i); + question.setDescription("Description " + i); + questionRepository.save(question); + } + return true; + } catch (Exception e) { + return false; + } + } + + private boolean deleteQuestions() { + try { + questionRepository.deleteAll(); + return true; + } catch (Exception e) { + return false; + } + } + @Test public void testGetQuestions() throws Exception { -// when(questionRepository.findAll()).thenReturn(List.of(new Question())); + for (int assertionNumber = 0; assertionNumber < 100; assertionNumber++) { + int pageSize = 20; - this.mockMvc - .perform(MockMvcRequestBuilders.get("/questions")) - .andExpect(MockMvcResultMatchers.status().isOk()); + if (!fillQuestions(assertionNumber)) { + throw new Exception("Failed to fill questions"); + } + + mockMvc.perform(get("/questions") + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) + .andExpect(MockMvcResultMatchers.jsonPath("$.content.length()", Matchers.equalTo(Math.min(assertionNumber, pageSize)))) + .andExpect(MockMvcResultMatchers.jsonPath("$.totalElements", Matchers.equalTo(assertionNumber))) // Assert total elements + .andExpect(MockMvcResultMatchers.jsonPath("$.totalPages", Matchers.equalTo((int) Math.ceil(assertionNumber / (double) pageSize)))); // Assert total pages for 10 items per page + + if (!deleteQuestions()) { + throw new Exception("Failed to delete questions"); + } + } } + } From bab3c3228d3c220621a6b51eb55064c6bd14f53c Mon Sep 17 00:00:00 2001 From: "zahar.kalosha" Date: Fri, 14 Jun 2024 11:04:23 +0300 Subject: [PATCH 6/9] Add QuestionController test --- .../controller/QuestionControllerTest.java | 137 ++++++++++++++++-- 1 file changed, 124 insertions(+), 13 deletions(-) diff --git a/src/test/java/com/example/postgresdemo/controller/QuestionControllerTest.java b/src/test/java/com/example/postgresdemo/controller/QuestionControllerTest.java index 4fcbda2..3abf16e 100644 --- a/src/test/java/com/example/postgresdemo/controller/QuestionControllerTest.java +++ b/src/test/java/com/example/postgresdemo/controller/QuestionControllerTest.java @@ -5,28 +5,19 @@ import org.hamcrest.Matchers; import org.junit.jupiter.api.Test; -import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.test.mock.mockito.MockBean; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.PageImpl; -import org.springframework.data.domain.PageRequest; -import org.springframework.data.domain.Pageable; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.ResultMatcher; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.web.context.WebApplicationContext; -import java.util.Arrays; -import java.util.List; +import java.nio.CharBuffer; import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.mockito.Mockito.when; import static org.springframework.test.web.client.match.MockRestRequestMatchers.jsonPath; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; @@ -75,8 +66,16 @@ private boolean deleteQuestions() { } } + private void deleteQuestionsWithExceptionOnFail() throws Exception { + if (!deleteQuestions()) { + throw new Exception("Failed to delete questions"); + } + } + @Test public void testGetQuestions() throws Exception { + deleteQuestionsWithExceptionOnFail(); + for (int assertionNumber = 0; assertionNumber < 100; assertionNumber++) { int pageSize = 20; @@ -92,10 +91,122 @@ public void testGetQuestions() throws Exception { .andExpect(MockMvcResultMatchers.jsonPath("$.totalElements", Matchers.equalTo(assertionNumber))) // Assert total elements .andExpect(MockMvcResultMatchers.jsonPath("$.totalPages", Matchers.equalTo((int) Math.ceil(assertionNumber / (double) pageSize)))); // Assert total pages for 10 items per page - if (!deleteQuestions()) { - throw new Exception("Failed to delete questions"); - } + deleteQuestionsWithExceptionOnFail(); } } + @Test + public void testCreateCorrectQuestion() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.post("/questions") + .contentType(MediaType.APPLICATION_JSON) + .content("{\n" + + " \"title\": \"Question 1\",\n" + + " \"description\": \"Description 1\"\n" + + "}")) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) + .andExpect(MockMvcResultMatchers.jsonPath("$.title", Matchers.equalTo("Question 1"))) + .andExpect(MockMvcResultMatchers.jsonPath("$.description", Matchers.equalTo("Description 1"))); + + deleteQuestionsWithExceptionOnFail(); + } + + @Test + public void testCreateQuestionWithoutTitle() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.post("/questions") + .contentType(MediaType.APPLICATION_JSON) + .content("{\n" + + " \"description\": \"Description\"\n" + + "}")) + .andExpect(status().is4xxClientError()); + + deleteQuestionsWithExceptionOnFail(); + } + + @Test + public void testCreateQuestionWithTitleLesThenThreeChars() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.post("/questions") + .contentType(MediaType.APPLICATION_JSON) + .content("{\n" + + " \"title\": \"Te\",\n" + + " \"description\": \"Description\"\n" + + "}")) + .andExpect(status().is4xxClientError()); + + deleteQuestionsWithExceptionOnFail(); + } + + @Test + public void testCreateQuestionWithTitleMoreThenHundredChars() throws Exception { + int numberOfChars = 101; + String title = CharBuffer.allocate(numberOfChars).toString().replace('\0', 'T'); + mockMvc.perform(MockMvcRequestBuilders.post("/questions") + .contentType(MediaType.APPLICATION_JSON) + .content("{\n" + + " \"title\": \"" + title + "\",\n" + + " \"description\": \"Description\"\n" + + "}")) + .andExpect(status().is4xxClientError()); + + deleteQuestionsWithExceptionOnFail(); + } + + @Test + public void testCreateQuestionWithoutDescription() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.post("/questions") + .contentType(MediaType.APPLICATION_JSON) + .content("{\n" + + " \"title\": \"Question 1\"\n" + + "}")) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) + .andExpect(MockMvcResultMatchers.jsonPath("$.title", Matchers.equalTo("Question 1"))) + .andExpect(MockMvcResultMatchers.jsonPath("$.description", Matchers.equalTo(null))); + + deleteQuestionsWithExceptionOnFail(); + } + + @Test + public void testUpdateQuestion() throws Exception { + deleteQuestionsWithExceptionOnFail(); + fillQuestions(1); + long questionId = questionRepository.findAll().get(0).getId(); + + mockMvc.perform(MockMvcRequestBuilders.put("/questions/" + questionId) + .contentType(MediaType.APPLICATION_JSON) + .content("{\n" + + " \"title\": \"Edited Question 1\",\n" + + " \"description\": \"Edited Description 1\"\n" + + "}")) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) + .andExpect(MockMvcResultMatchers.jsonPath("$.title", Matchers.equalTo("Edited Question 1"))) + .andExpect(MockMvcResultMatchers.jsonPath("$.description", Matchers.equalTo("Edited Description 1"))); + + deleteQuestionsWithExceptionOnFail(); + } + + @Test + public void testUpdateQuestionWithNonExistingId() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.put("/questions/1") + .contentType(MediaType.APPLICATION_JSON) + .content("{\n" + + " \"title\": \"Edited Question 1\",\n" + + " \"description\": \"Edited Description 1\"\n" + + "}")) + .andExpect(status().is4xxClientError()); + } + + @Test + public void testDeleteQuestion() throws Exception { + deleteQuestionsWithExceptionOnFail(); + fillQuestions(1); + long questionId = questionRepository.findAll().get(0).getId(); + + mockMvc.perform(MockMvcRequestBuilders.delete("/questions/" + questionId) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()); + + deleteQuestionsWithExceptionOnFail(); + } } From 27d8a89778d04ee432a63e2f8d0aee1770098e27 Mon Sep 17 00:00:00 2001 From: "zahar.kalosha" Date: Fri, 14 Jun 2024 11:27:57 +0300 Subject: [PATCH 7/9] Fix antipatterns in tests --- .../controller/QuestionControllerTest.java | 105 +++++++----------- 1 file changed, 43 insertions(+), 62 deletions(-) diff --git a/src/test/java/com/example/postgresdemo/controller/QuestionControllerTest.java b/src/test/java/com/example/postgresdemo/controller/QuestionControllerTest.java index 3abf16e..4ce1cac 100644 --- a/src/test/java/com/example/postgresdemo/controller/QuestionControllerTest.java +++ b/src/test/java/com/example/postgresdemo/controller/QuestionControllerTest.java @@ -4,6 +4,8 @@ import com.example.postgresdemo.repository.QuestionRepository; import org.hamcrest.Matchers; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; @@ -38,61 +40,52 @@ public class QuestionControllerTest { @Autowired private QuestionController questionController; - @Test - public void testCreateMockMvc() { - assertNotNull(mockMvc); - } - - private boolean fillQuestions(Integer number) { - try { - for (int i = 0; i < number; i++) { - Question question = new Question(); - question.setTitle("Question " + i); - question.setDescription("Description " + i); - questionRepository.save(question); - } - return true; - } catch (Exception e) { - return false; + private void fillQuestions(Integer number) { + for (int i = 0; i < number; i++) { + Question question = new Question(); + question.setTitle("Question " + i); + question.setDescription("Description " + i); + questionRepository.save(question); } } - private boolean deleteQuestions() { - try { - questionRepository.deleteAll(); - return true; - } catch (Exception e) { - return false; - } - } - - private void deleteQuestionsWithExceptionOnFail() throws Exception { - if (!deleteQuestions()) { - throw new Exception("Failed to delete questions"); - } + @BeforeEach + @AfterEach + public void deleteQuestions() { + questionRepository.deleteAll(); } @Test - public void testGetQuestions() throws Exception { - deleteQuestionsWithExceptionOnFail(); + public void testGetQuestionsWithAmountLessThanPageSize() throws Exception { + int assertionNumber = 10; + int pageSize = 20; - for (int assertionNumber = 0; assertionNumber < 100; assertionNumber++) { - int pageSize = 20; + fillQuestions(assertionNumber); - if (!fillQuestions(assertionNumber)) { - throw new Exception("Failed to fill questions"); - } + mockMvc.perform(get("/questions") + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) + .andExpect(MockMvcResultMatchers.jsonPath("$.content.length()", Matchers.equalTo(assertionNumber))) + .andExpect(MockMvcResultMatchers.jsonPath("$.totalElements", Matchers.equalTo(assertionNumber))) + .andExpect(MockMvcResultMatchers.jsonPath("$.totalPages", Matchers.equalTo(1))); + } - mockMvc.perform(get("/questions") - .contentType(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) - .andExpect(MockMvcResultMatchers.jsonPath("$.content.length()", Matchers.equalTo(Math.min(assertionNumber, pageSize)))) - .andExpect(MockMvcResultMatchers.jsonPath("$.totalElements", Matchers.equalTo(assertionNumber))) // Assert total elements - .andExpect(MockMvcResultMatchers.jsonPath("$.totalPages", Matchers.equalTo((int) Math.ceil(assertionNumber / (double) pageSize)))); // Assert total pages for 10 items per page + @Test + public void testGetQuestionsWithAmountMoreThanPageSize() throws Exception { + int assertionNumber = 30; + int pageSize = 20; + int totalPages = (int) Math.ceil(assertionNumber / (double) pageSize); - deleteQuestionsWithExceptionOnFail(); - } + fillQuestions(assertionNumber); + + mockMvc.perform(get("/questions") + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) + .andExpect(MockMvcResultMatchers.jsonPath("$.content.length()", Matchers.equalTo(pageSize))) + .andExpect(MockMvcResultMatchers.jsonPath("$.totalElements", Matchers.equalTo(assertionNumber))) + .andExpect(MockMvcResultMatchers.jsonPath("$.totalPages", Matchers.equalTo(totalPages))); } @Test @@ -107,8 +100,6 @@ public void testCreateCorrectQuestion() throws Exception { .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.jsonPath("$.title", Matchers.equalTo("Question 1"))) .andExpect(MockMvcResultMatchers.jsonPath("$.description", Matchers.equalTo("Description 1"))); - - deleteQuestionsWithExceptionOnFail(); } @Test @@ -119,8 +110,6 @@ public void testCreateQuestionWithoutTitle() throws Exception { " \"description\": \"Description\"\n" + "}")) .andExpect(status().is4xxClientError()); - - deleteQuestionsWithExceptionOnFail(); } @Test @@ -132,14 +121,13 @@ public void testCreateQuestionWithTitleLesThenThreeChars() throws Exception { " \"description\": \"Description\"\n" + "}")) .andExpect(status().is4xxClientError()); - - deleteQuestionsWithExceptionOnFail(); } @Test public void testCreateQuestionWithTitleMoreThenHundredChars() throws Exception { int numberOfChars = 101; String title = CharBuffer.allocate(numberOfChars).toString().replace('\0', 'T'); + mockMvc.perform(MockMvcRequestBuilders.post("/questions") .contentType(MediaType.APPLICATION_JSON) .content("{\n" + @@ -147,8 +135,6 @@ public void testCreateQuestionWithTitleMoreThenHundredChars() throws Exception { " \"description\": \"Description\"\n" + "}")) .andExpect(status().is4xxClientError()); - - deleteQuestionsWithExceptionOnFail(); } @Test @@ -162,13 +148,10 @@ public void testCreateQuestionWithoutDescription() throws Exception { .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.jsonPath("$.title", Matchers.equalTo("Question 1"))) .andExpect(MockMvcResultMatchers.jsonPath("$.description", Matchers.equalTo(null))); - - deleteQuestionsWithExceptionOnFail(); } @Test public void testUpdateQuestion() throws Exception { - deleteQuestionsWithExceptionOnFail(); fillQuestions(1); long questionId = questionRepository.findAll().get(0).getId(); @@ -182,13 +165,14 @@ public void testUpdateQuestion() throws Exception { .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(MockMvcResultMatchers.jsonPath("$.title", Matchers.equalTo("Edited Question 1"))) .andExpect(MockMvcResultMatchers.jsonPath("$.description", Matchers.equalTo("Edited Description 1"))); - - deleteQuestionsWithExceptionOnFail(); } @Test public void testUpdateQuestionWithNonExistingId() throws Exception { - mockMvc.perform(MockMvcRequestBuilders.put("/questions/1") + fillQuestions(1); + long questionId = questionRepository.findAll().get(0).getId(); + + mockMvc.perform(MockMvcRequestBuilders.put("/questions/" + (questionId + 1)) .contentType(MediaType.APPLICATION_JSON) .content("{\n" + " \"title\": \"Edited Question 1\",\n" + @@ -199,14 +183,11 @@ public void testUpdateQuestionWithNonExistingId() throws Exception { @Test public void testDeleteQuestion() throws Exception { - deleteQuestionsWithExceptionOnFail(); fillQuestions(1); long questionId = questionRepository.findAll().get(0).getId(); mockMvc.perform(MockMvcRequestBuilders.delete("/questions/" + questionId) .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()); - - deleteQuestionsWithExceptionOnFail(); } } From ae1f093fd03a7d13eb847b72def06e6625cd102b Mon Sep 17 00:00:00 2001 From: "zahar.kalosha" Date: Fri, 14 Jun 2024 13:43:48 +0300 Subject: [PATCH 8/9] Fix tests methods --- .../controller/QuestionControllerTest.java | 23 +++++++++---------- 1 file changed, 11 insertions(+), 12 deletions(-) diff --git a/src/test/java/com/example/postgresdemo/controller/QuestionControllerTest.java b/src/test/java/com/example/postgresdemo/controller/QuestionControllerTest.java index 4ce1cac..7e238d9 100644 --- a/src/test/java/com/example/postgresdemo/controller/QuestionControllerTest.java +++ b/src/test/java/com/example/postgresdemo/controller/QuestionControllerTest.java @@ -49,14 +49,13 @@ private void fillQuestions(Integer number) { } } - @BeforeEach @AfterEach - public void deleteQuestions() { + void deleteQuestions() { questionRepository.deleteAll(); } @Test - public void testGetQuestionsWithAmountLessThanPageSize() throws Exception { + void testGetQuestionsWithAmountLessThanPageSize() throws Exception { int assertionNumber = 10; int pageSize = 20; @@ -72,7 +71,7 @@ public void testGetQuestionsWithAmountLessThanPageSize() throws Exception { } @Test - public void testGetQuestionsWithAmountMoreThanPageSize() throws Exception { + void testGetQuestionsWithAmountMoreThanPageSize() throws Exception { int assertionNumber = 30; int pageSize = 20; int totalPages = (int) Math.ceil(assertionNumber / (double) pageSize); @@ -89,7 +88,7 @@ public void testGetQuestionsWithAmountMoreThanPageSize() throws Exception { } @Test - public void testCreateCorrectQuestion() throws Exception { + void testCreateCorrectQuestion() throws Exception { mockMvc.perform(MockMvcRequestBuilders.post("/questions") .contentType(MediaType.APPLICATION_JSON) .content("{\n" + @@ -103,7 +102,7 @@ public void testCreateCorrectQuestion() throws Exception { } @Test - public void testCreateQuestionWithoutTitle() throws Exception { + void testCreateQuestionWithoutTitle() throws Exception { mockMvc.perform(MockMvcRequestBuilders.post("/questions") .contentType(MediaType.APPLICATION_JSON) .content("{\n" + @@ -113,7 +112,7 @@ public void testCreateQuestionWithoutTitle() throws Exception { } @Test - public void testCreateQuestionWithTitleLesThenThreeChars() throws Exception { + void testCreateQuestionWithTitleLesThenThreeChars() throws Exception { mockMvc.perform(MockMvcRequestBuilders.post("/questions") .contentType(MediaType.APPLICATION_JSON) .content("{\n" + @@ -124,7 +123,7 @@ public void testCreateQuestionWithTitleLesThenThreeChars() throws Exception { } @Test - public void testCreateQuestionWithTitleMoreThenHundredChars() throws Exception { + void testCreateQuestionWithTitleMoreThenHundredChars() throws Exception { int numberOfChars = 101; String title = CharBuffer.allocate(numberOfChars).toString().replace('\0', 'T'); @@ -138,7 +137,7 @@ public void testCreateQuestionWithTitleMoreThenHundredChars() throws Exception { } @Test - public void testCreateQuestionWithoutDescription() throws Exception { + void testCreateQuestionWithoutDescription() throws Exception { mockMvc.perform(MockMvcRequestBuilders.post("/questions") .contentType(MediaType.APPLICATION_JSON) .content("{\n" + @@ -151,7 +150,7 @@ public void testCreateQuestionWithoutDescription() throws Exception { } @Test - public void testUpdateQuestion() throws Exception { + void testUpdateQuestion() throws Exception { fillQuestions(1); long questionId = questionRepository.findAll().get(0).getId(); @@ -168,7 +167,7 @@ public void testUpdateQuestion() throws Exception { } @Test - public void testUpdateQuestionWithNonExistingId() throws Exception { + void testUpdateQuestionWithNonExistingId() throws Exception { fillQuestions(1); long questionId = questionRepository.findAll().get(0).getId(); @@ -182,7 +181,7 @@ public void testUpdateQuestionWithNonExistingId() throws Exception { } @Test - public void testDeleteQuestion() throws Exception { + void testDeleteQuestion() throws Exception { fillQuestions(1); long questionId = questionRepository.findAll().get(0).getId(); From 3cd121997b38706018499e96590ea01e75653b3a Mon Sep 17 00:00:00 2001 From: "zahar.kalosha" Date: Fri, 14 Jun 2024 16:46:32 +0300 Subject: [PATCH 9/9] Clean tests class --- .../controller/QuestionControllerTest.java | 27 +++++++------------ 1 file changed, 9 insertions(+), 18 deletions(-) diff --git a/src/test/java/com/example/postgresdemo/controller/QuestionControllerTest.java b/src/test/java/com/example/postgresdemo/controller/QuestionControllerTest.java index 7e238d9..15229c4 100644 --- a/src/test/java/com/example/postgresdemo/controller/QuestionControllerTest.java +++ b/src/test/java/com/example/postgresdemo/controller/QuestionControllerTest.java @@ -5,7 +5,6 @@ import org.hamcrest.Matchers; import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; @@ -14,13 +13,10 @@ import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; -import org.springframework.web.context.WebApplicationContext; import java.nio.CharBuffer; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.springframework.test.web.client.match.MockRestRequestMatchers.jsonPath; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @@ -32,22 +28,8 @@ public class QuestionControllerTest { @Autowired private QuestionRepository questionRepository; - @Autowired - private WebApplicationContext webApplicationContext; - @Autowired private MockMvc mockMvc; - @Autowired - private QuestionController questionController; - - private void fillQuestions(Integer number) { - for (int i = 0; i < number; i++) { - Question question = new Question(); - question.setTitle("Question " + i); - question.setDescription("Description " + i); - questionRepository.save(question); - } - } @AfterEach void deleteQuestions() { @@ -189,4 +171,13 @@ void testDeleteQuestion() throws Exception { .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()); } + + private void fillQuestions(Integer number) { + for (int i = 0; i < number; i++) { + Question question = new Question(); + question.setTitle("Question " + i); + question.setDescription("Description " + i); + questionRepository.save(question); + } + } }