Skip to content
Snippets Groups Projects
Commit 6fa0b58e authored by Haoyu Sun's avatar Haoyu Sun
Browse files

Merge branch '4-Light-weight-Mock-MVC' into 'main'

haoyusunTEST

Closes #4

See merge request !60
parents ef1ec53e 8eeceabb
No related branches found
No related tags found
1 merge request!60haoyusunTEST
...@@ -28,6 +28,7 @@ dependencies { ...@@ -28,6 +28,7 @@ dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web' implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-jdbc' implementation 'org.springframework.boot:spring-boot-starter-jdbc'
//from https://mariadb.com/kb/en/java-connector-using-gradle/ //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:3.3.3'
// implementation 'org.mariadb.jdbc:mariadb-java-client:2.1.2' // implementation 'org.mariadb.jdbc:mariadb-java-client:2.1.2'
...@@ -42,6 +43,7 @@ dependencies { ...@@ -42,6 +43,7 @@ dependencies {
annotationProcessor 'org.projectlombok:lombok' annotationProcessor 'org.projectlombok:lombok'
testImplementation 'org.springframework.boot:spring-boot-starter-test' testImplementation 'org.springframework.boot:spring-boot-starter-test'
testRuntimeOnly 'org.junit.platform:junit-platform-launcher' testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
testImplementation 'org.springframework.security:spring-security-test'
} }
tasks.named('test') { tasks.named('test') {
......
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 Full container and servlet
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");
}
}
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());
}
}
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 Integration
@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);
}
//
}
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
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment