From 21468ae56d73043c67d33c611ed49d2b0667c93a Mon Sep 17 00:00:00 2001
From: Haoyu Sun <SunH26@cardiff.ac.uk>
Date: Thu, 6 Feb 2025 09:41:17 +0000
Subject: [PATCH 1/4] TrueUnitTests for getter and setter

---
 .../uk/ac/cf/spring/demo/TrueUnitTests.java   | 61 +++++++++++++++++++
 1 file changed, 61 insertions(+)
 create mode 100644 src/test/java/uk/ac/cf/spring/demo/TrueUnitTests.java

diff --git a/src/test/java/uk/ac/cf/spring/demo/TrueUnitTests.java b/src/test/java/uk/ac/cf/spring/demo/TrueUnitTests.java
new file mode 100644
index 0000000..5671d6f
--- /dev/null
+++ b/src/test/java/uk/ac/cf/spring/demo/TrueUnitTests.java
@@ -0,0 +1,61 @@
+package uk.ac.cf.spring.demo;
+
+import org.junit.jupiter.api.Test;
+import uk.ac.cf.spring.demo.sports.match.MatchItem;
+
+import java.time.LocalDateTime;
+public class TrueUnitTests {
+    //    测试MatchItem的getter和setter方法
+    @Test
+    public void testGettersAndSetters() {
+        // 创建一个 MatchItem 对象
+        MatchItem matchItem = new MatchItem();
+
+        // 测试 id 的 getter 和 setter
+        matchItem.setId(1L);
+        assert matchItem.getId() == 1L : "Test failed for id";
+
+        // 测试 sport 的 getter 和 setter
+        matchItem.setSport("football");
+        assert "football".equals(matchItem.getSport()) : "Test failed for sport";
+
+        // 测试 playerAId 的 getter 和 setter
+        matchItem.setPlayerAId(10L);
+        assert matchItem.getPlayerAId() == 10L : "Test failed for playerAId";
+
+        // 测试 playerBId 的 getter 和 setter
+        matchItem.setPlayerBId(20L);
+        assert matchItem.getPlayerBId() == 20L : "Test failed for playerBId";
+
+        // 测试 PlanTime 的 getter 和 setter
+        LocalDateTime now = LocalDateTime.now();
+        matchItem.setPlanTime(now);
+        assert now.equals(matchItem.getPlanTime()) : "Test failed for PlanTime";
+
+        // 测试 status 的 getter 和 setter
+        matchItem.setStatus("confirmed");
+        assert "confirmed".equals(matchItem.getStatus()) : "Test failed for status";
+
+        // 测试 scoreA 的 getter 和 setter
+        matchItem.setScoreA(5L);
+        assert matchItem.getScoreA() == 5L : "Test failed for scoreA";
+
+        // 测试 scoreB 的 getter 和 setter
+        matchItem.setScoreB(3L);
+        assert matchItem.getScoreB() == 3L : "Test failed for scoreB";
+
+        // 测试 confirmByA 的 getter 和 setter
+        matchItem.setConfirmByA(true);
+        assert matchItem.getConfirmByA() : "Test failed for confirmByA";
+
+        // 测试 confirmByB 的 getter 和 setter
+        matchItem.setConfirmByB(false);
+        assert !matchItem.getConfirmByB() : "Test failed for confirmByB";
+
+        // 测试 winnerId 的 getter 和 setter
+        matchItem.setWinnerId(10L);
+        assert matchItem.getWinnerId() == 10L : "Test failed for winnerId";
+
+    }
+
+}
\ No newline at end of file
-- 
GitLab


From 0fe0209b2729f4bfab743ce9cc434057e5cfa87c Mon Sep 17 00:00:00 2001
From: Haoyu Sun <SunH26@cardiff.ac.uk>
Date: Thu, 6 Feb 2025 10:30:01 +0000
Subject: [PATCH 2/4] System tests Full container and servlet with db and no db

---
 .../ac/cf/spring/demo/HTTPConnectionTest.java | 49 +++++++++++++++++++
 1 file changed, 49 insertions(+)
 create mode 100644 src/test/java/uk/ac/cf/spring/demo/HTTPConnectionTest.java

diff --git a/src/test/java/uk/ac/cf/spring/demo/HTTPConnectionTest.java b/src/test/java/uk/ac/cf/spring/demo/HTTPConnectionTest.java
new file mode 100644
index 0000000..b7eaec4
--- /dev/null
+++ b/src/test/java/uk/ac/cf/spring/demo/HTTPConnectionTest.java
@@ -0,0 +1,49 @@
+package uk.ac.cf.spring.demo;
+
+import org.junit.jupiter.api.Test;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.boot.test.web.client.TestRestTemplate;
+import org.springframework.http.ResponseEntity;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
+// System Test
+public class HTTPConnectionTest {
+    @Value(value="${local.server.port}")
+    private int port;
+
+    @Autowired
+    private TestRestTemplate restTemplate;
+    //    Full container and servlet and no database
+    @Test
+    public void greetingShouldReturnDefaultMessage() throws Exception {
+        assertThat(this.restTemplate.getForObject("http://localhost:" + port + "/html/matchSchedule.html",
+                String.class)).contains("Sport");
+    }
+//    Full container and servlet with Test db
+    @Test
+    public void dbMatchTest() throws Exception {
+        // 准备登录数据
+        Map<String, String> loginData = new HashMap<>();
+        loginData.put("email", "shy@creditsafe.com");
+        loginData.put("password", "shy");
+
+        // 向登录接口发送 POST 请求,模拟登录
+        ResponseEntity<String> loginResponse = this.restTemplate.postForEntity(
+                "http://localhost:" + port + "/api/users/login",
+                loginData,
+                String.class);
+
+        // 确认登录成功
+        assertThat(loginResponse.getBody()).contains("Login successful");
+        // 检查接口是否有pools字段
+        assertThat(this.restTemplate.getForObject("http://localhost:" + port + "/match",
+                String.class)).contains("Pools");
+}
+}
-- 
GitLab


From 7f395a058c0a2741088edf39dad57a64a749d2e7 Mon Sep 17 00:00:00 2001
From: Haoyu Sun <SunH26@cardiff.ac.uk>
Date: Thu, 6 Feb 2025 10:53:43 +0000
Subject: [PATCH 3/4] Full container Mock MVC - prepare for Light weight
 MockMVC test

---
 build.gradle                                  |  1 +
 .../demo/MatchControllerIngrationTest.java    | 62 +++++++++++++++++++
 2 files changed, 63 insertions(+)
 create mode 100644 src/test/java/uk/ac/cf/spring/demo/MatchControllerIngrationTest.java

diff --git a/build.gradle b/build.gradle
index 2d1c437..072e03c 100644
--- a/build.gradle
+++ b/build.gradle
@@ -28,6 +28,7 @@ dependencies {
 	implementation 'org.springframework.boot:spring-boot-starter-web'
 	implementation 'org.springframework.boot:spring-boot-starter-jdbc'
 	//from https://mariadb.com/kb/en/java-connector-using-gradle/
+	implementation 'junit:junit:4.12'
 
 	implementation 'org.mariadb.jdbc:mariadb-java-client:3.3.3'
 	// implementation 'org.mariadb.jdbc:mariadb-java-client:2.1.2'
diff --git a/src/test/java/uk/ac/cf/spring/demo/MatchControllerIngrationTest.java b/src/test/java/uk/ac/cf/spring/demo/MatchControllerIngrationTest.java
new file mode 100644
index 0000000..212b363
--- /dev/null
+++ b/src/test/java/uk/ac/cf/spring/demo/MatchControllerIngrationTest.java
@@ -0,0 +1,62 @@
+package uk.ac.cf.spring.demo;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.InjectMocks;
+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.test.web.servlet.MockMvc;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
+import uk.ac.cf.spring.demo.sports.match.MatchController;
+import uk.ac.cf.spring.demo.sports.match.MatchItem;
+import uk.ac.cf.spring.demo.sports.match.MatchService;
+
+import java.util.Arrays;
+import java.util.List;
+
+import static org.mockito.Mockito.*;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
+//Full container Mock MVC
+@SpringBootTest
+@AutoConfigureMockMvc
+public class MatchControllerIngrationTest {
+
+    @MockBean
+    private MatchService matchService;
+
+//    @InjectMocks
+//    private MatchController matchController;
+
+    @Autowired
+    private MockMvc mockMvc;
+    // Integration Test with Mock MVC
+    @Test
+    void testGetAllMatches() throws Exception {
+        MatchItem match1 = new MatchItem(1L, "Soccer", 1L, 2L, null, "completed", 2L, 3L, true, true, 2L);
+        List<MatchItem> matches = Arrays.asList(match1);
+
+        when(matchService.getMatchItems()).thenReturn(matches);
+
+        mockMvc.perform(MockMvcRequestBuilders.get("/match"))
+                .andExpect(status().isOk());
+
+        verify(matchService, times(1)).getMatchItems();
+    }
+
+    //    Integration Test with Mock MVC
+    @Test
+    void testGetMatchById() throws Exception {
+        MatchItem match1 = new MatchItem(1L, "Soccer", 1L, 2L, null, "completed", 2L, 3L, true, true, 2L);
+
+        when(matchService.getMatchItemById(1L)).thenReturn(match1);
+
+        mockMvc.perform(MockMvcRequestBuilders.get("/match/1"))
+                .andExpect(status().isOk());
+
+        verify(matchService, times(1)).getMatchItemById(1L);
+    }
+
+    //
+}
-- 
GitLab


From b693c872942f41c5f416d46597cfcaaa9dd04c68 Mon Sep 17 00:00:00 2001
From: Haoyu Sun <SunH26@cardiff.ac.uk>
Date: Thu, 6 Feb 2025 12:09:26 +0000
Subject: [PATCH 4/4] Lightweight Mock MVC Mock DB/Repo response Unit or
 Integration @RunWith(SpringRunner.class) @WebMvcTest(GeneralController.class)

---
 build.gradle                                  |   1 +
 .../ac/cf/spring/demo/HTTPConnectionTest.java |   2 +-
 .../spring/demo/LightweightMockMVCTests.java  | 109 ++++++++++++++++++
 .../demo/MatchControllerIngrationTest.java    |   2 +-
 4 files changed, 112 insertions(+), 2 deletions(-)
 create mode 100644 src/test/java/uk/ac/cf/spring/demo/LightweightMockMVCTests.java

diff --git a/build.gradle b/build.gradle
index 072e03c..0a64192 100644
--- a/build.gradle
+++ b/build.gradle
@@ -43,6 +43,7 @@ dependencies {
 	annotationProcessor 'org.projectlombok:lombok'
 	testImplementation 'org.springframework.boot:spring-boot-starter-test'
 	testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
+	testImplementation 'org.springframework.security:spring-security-test'
 }
 
 tasks.named('test') {
diff --git a/src/test/java/uk/ac/cf/spring/demo/HTTPConnectionTest.java b/src/test/java/uk/ac/cf/spring/demo/HTTPConnectionTest.java
index b7eaec4..265883f 100644
--- a/src/test/java/uk/ac/cf/spring/demo/HTTPConnectionTest.java
+++ b/src/test/java/uk/ac/cf/spring/demo/HTTPConnectionTest.java
@@ -13,7 +13,7 @@ import java.util.Map;
 import static org.assertj.core.api.Assertions.assertThat;
 
 @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
-// System Test
+// System Test Full container and servlet
 public class HTTPConnectionTest {
     @Value(value="${local.server.port}")
     private int port;
diff --git a/src/test/java/uk/ac/cf/spring/demo/LightweightMockMVCTests.java b/src/test/java/uk/ac/cf/spring/demo/LightweightMockMVCTests.java
new file mode 100644
index 0000000..4f58232
--- /dev/null
+++ b/src/test/java/uk/ac/cf/spring/demo/LightweightMockMVCTests.java
@@ -0,0 +1,109 @@
+package uk.ac.cf.spring.demo;
+
+import org.junit.jupiter.api.Test;
+import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
+import org.springframework.boot.test.mock.mockito.MockBean;
+import org.springframework.context.annotation.Import;
+import org.springframework.http.MediaType;
+import org.springframework.security.test.context.support.WithMockUser;
+import org.springframework.test.context.junit4.SpringRunner;
+import org.springframework.test.web.servlet.MockMvc;
+import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
+import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
+import uk.ac.cf.spring.demo.sports.match.MatchController;
+import uk.ac.cf.spring.demo.sports.match.MatchItem;
+import uk.ac.cf.spring.demo.sports.match.MatchService;
+import uk.ac.cf.spring.demo.sports.security.SecurityConfig;
+
+import java.time.LocalDateTime;
+import java.util.Arrays;
+import java.util.List;
+
+import static org.mockito.Mockito.when;
+//Lightweight Mock MVC
+// Unit or Integration
+
+@RunWith(SpringRunner.class)
+@WebMvcTest(MatchController.class)
+@Import(SecurityConfig.class)
+public class LightweightMockMVCTests {
+
+    @Autowired
+    private MockMvc mockMvc;
+
+    @MockBean
+    private MatchService matchService;
+    @WithMockUser(username = "shy", password = "shy")
+    @Test
+    public void testGetAllMatchItems() throws Exception {
+        // Prepare match items with specific data
+        MatchItem matchItem1 = new MatchItem(1L, "Pools", 1L, 2L, LocalDateTime.now(), "pending", 0L, 0L, false, false, 0L);
+        MatchItem matchItem2 = new MatchItem(2L, "Darts", 3L, 4L, LocalDateTime.now(), "pending", 0L, 0L, false, false, 0L);
+
+        List<MatchItem> matchItems = Arrays.asList(matchItem1, matchItem2);
+
+        // Mocking the service method
+        when(matchService.getMatchItems()).thenReturn(matchItems);
+
+        // Perform the GET request and verify the result
+        mockMvc.perform(MockMvcRequestBuilders.get("/match"))
+                .andExpect(MockMvcResultMatchers.status().isOk())
+                .andExpect(MockMvcResultMatchers.jsonPath("$[0].id").value(1))
+                .andExpect(MockMvcResultMatchers.jsonPath("$[0].sport").value("Pools"))
+                .andExpect(MockMvcResultMatchers.jsonPath("$[1].id").value(2))
+                .andExpect(MockMvcResultMatchers.jsonPath("$[1].sport").value("Darts"));
+    }
+
+    @WithMockUser(username = "shy", password = "shy")
+    @Test
+    public void testGetMatchItemById() throws Exception {
+        // Prepare a specific match item
+        MatchItem matchItem = new MatchItem(1L, "Pools", 1L, 2L, LocalDateTime.now(), "pending", 0L, 0L, false, false, 0L);
+
+        // Mocking the service method
+        when(matchService.getMatchItemById(1L)).thenReturn(matchItem);
+
+        // Perform the GET request and verify the result
+        mockMvc.perform(MockMvcRequestBuilders.get("/match/1"))
+                .andExpect(MockMvcResultMatchers.status().isOk())
+                .andExpect(MockMvcResultMatchers.jsonPath("$.id").value(1))
+                .andExpect(MockMvcResultMatchers.jsonPath("$.sport").value("Pools"));
+    }
+    @WithMockUser(username = "shy", password = "shy")
+    @Test
+    public void testAddMatchItem() throws Exception {
+        // Prepare the match item to be added
+        MatchItem matchItem = new MatchItem(null, "Tennis", 1L, 2L, LocalDateTime.now(), "pending", 0L, 0L, false, false, 0L);
+
+        // Perform the POST request
+        mockMvc.perform(MockMvcRequestBuilders.post("/match")
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content("{\"sport\":\"Tennis\",\"team1\":1,\"team2\":2,\"date\":\"" + LocalDateTime.now() + "\",\"status\":\"pending\",\"score1\":0,\"score2\":0,\"isLive\":false,\"isFinished\":false,\"duration\":0}"))
+                .andExpect(MockMvcResultMatchers.status().isOk());
+    }
+    @WithMockUser(username = "shy", password = "shy")
+    @Test
+    public void testUpdateMatchItem() throws Exception {
+        // Prepare the match item to be updated
+        MatchItem matchItem = new MatchItem(1L, "Pools", 1L, 2L, LocalDateTime.now(), "pending", 0L, 0L, false, false, 0L);
+
+        // Mocking the service method
+        when(matchService.getMatchItemById(1L)).thenReturn(matchItem);
+
+        // Perform the PUT request
+        mockMvc.perform(MockMvcRequestBuilders.put("/match/1")
+                        .contentType(MediaType.APPLICATION_JSON)
+                        .content("{\"id\":1,\"sport\":\"Pools\",\"team1\":1,\"team2\":2,\"date\":\"" + LocalDateTime.now() + "\",\"status\":\"pending\",\"score1\":0,\"score2\":0,\"isLive\":false,\"isFinished\":false,\"duration\":0}"))
+                .andExpect(MockMvcResultMatchers.status().isOk());
+    }
+    @WithMockUser(username = "shy", password = "shy")
+    @Test
+    public void testDeleteMatchItem() throws Exception {
+        // Perform the DELETE request
+        mockMvc.perform(MockMvcRequestBuilders.delete("/match/1"))
+                .andExpect(MockMvcResultMatchers.status().isOk());
+    }
+}
+
diff --git a/src/test/java/uk/ac/cf/spring/demo/MatchControllerIngrationTest.java b/src/test/java/uk/ac/cf/spring/demo/MatchControllerIngrationTest.java
index 212b363..f651d12 100644
--- a/src/test/java/uk/ac/cf/spring/demo/MatchControllerIngrationTest.java
+++ b/src/test/java/uk/ac/cf/spring/demo/MatchControllerIngrationTest.java
@@ -18,7 +18,7 @@ import java.util.List;
 
 import static org.mockito.Mockito.*;
 import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
-//Full container Mock MVC
+//Full container Mock MVC Integration
 @SpringBootTest
 @AutoConfigureMockMvc
 public class MatchControllerIngrationTest {
-- 
GitLab