- 实现了登录功能的单元测试、集成测试、系统测试和验收测试 - 修复了测试中的循环依赖、空指针异常和事务管理问题 - 配置了JaCoCo代码覆盖率工具,生成了详细的覆盖率报告 - 所有测试均通过,代码覆盖率报告已生成release
parent
b18f71df26
commit
49e91fc391
@ -0,0 +1,18 @@
|
||||
package com.atm.config;
|
||||
|
||||
import org.springframework.boot.test.context.TestConfiguration;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
|
||||
/**
|
||||
* 测试配置类
|
||||
*/
|
||||
@TestConfiguration
|
||||
public class TestConfig {
|
||||
|
||||
@Bean
|
||||
public PasswordEncoder passwordEncoder() {
|
||||
return new BCryptPasswordEncoder();
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,26 @@
|
||||
package com.atm.config;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Profile;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
||||
import org.springframework.security.web.SecurityFilterChain;
|
||||
|
||||
/**
|
||||
* 测试环境的安全配置
|
||||
*/
|
||||
@Configuration
|
||||
@EnableWebSecurity
|
||||
@Profile("test")
|
||||
public class TestSecurityConfig {
|
||||
|
||||
@Bean
|
||||
public SecurityFilterChain testFilterChain(HttpSecurity http) throws Exception {
|
||||
http.csrf(csrf -> csrf.disable())
|
||||
.authorizeHttpRequests(auth -> auth
|
||||
.anyRequest().permitAll()
|
||||
);
|
||||
return http.build();
|
||||
}
|
||||
}
|
||||
@ -1,55 +1,29 @@
|
||||
package com.atm.controller;
|
||||
|
||||
import org.junit.Assert;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
import com.atm.controller.Validate;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class ValidateTest extends junit.framework.TestCase {
|
||||
public class ValidateTest {
|
||||
|
||||
/**
|
||||
*
|
||||
* @param arg0
|
||||
*/
|
||||
public ValidateTest(String arg0) {
|
||||
super(arg0);
|
||||
@Test
|
||||
public void testIsNumeric() {
|
||||
assertTrue(Validate.isNumeric("123456"));
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param args
|
||||
*/
|
||||
public static void main(String[] args) {
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @exception Exception
|
||||
*/
|
||||
protected void setUp()
|
||||
throws Exception {
|
||||
super.setUp();
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @exception Exception
|
||||
*/
|
||||
protected void tearDown()
|
||||
throws Exception {
|
||||
super.tearDown();
|
||||
}
|
||||
|
||||
public final void testIsNumeric() {
|
||||
Assert.assertTrue(Validate.isNumeric("123456"));
|
||||
}
|
||||
public final void testIsNumeric_Failed() {
|
||||
Assert.assertFalse(Validate.isNumeric("12345d"));
|
||||
|
||||
@Test
|
||||
public void testIsNumeric_Failed() {
|
||||
assertFalse(Validate.isNumeric("12345d"));
|
||||
}
|
||||
public final void testLengthValidate() {
|
||||
Assert.assertTrue(Validate.lengthValidate("123456"));
|
||||
|
||||
@Test
|
||||
public void testLengthValidate() {
|
||||
assertTrue(Validate.lengthValidate("123456"));
|
||||
}
|
||||
public final void testLengthValidate_Failed() {
|
||||
Assert.assertFalse(Validate.lengthValidate("1234567"));
|
||||
|
||||
@Test
|
||||
public void testLengthValidate_Failed() {
|
||||
assertFalse(Validate.lengthValidate("1234567"));
|
||||
}
|
||||
}// end ValidateTest
|
||||
}
|
||||
@ -1,16 +1,15 @@
|
||||
package com.atm.dao;
|
||||
|
||||
import org.junit.runners.Suite;
|
||||
import org.junit.runner.RunWith;
|
||||
import junit.framework.TestSuite;
|
||||
import junit.framework.Test;
|
||||
import org.junit.platform.suite.api.SelectClasses;
|
||||
import org.junit.platform.suite.api.Suite;
|
||||
import org.junit.platform.suite.api.SuiteDisplayName;
|
||||
|
||||
@RunWith(Suite.class)
|
||||
@Suite.SuiteClasses({ com.atm.dao.LoginTest.class, com.atm.controller.ValidateTest.class })
|
||||
@Suite
|
||||
@SuiteDisplayName("Login Integrated Test Suite")
|
||||
@SelectClasses({
|
||||
com.atm.dao.LoginTest.class,
|
||||
com.atm.controller.ValidateTest.class
|
||||
})
|
||||
public class LoginIntegratedTest {
|
||||
|
||||
//public static Test suit() {
|
||||
// TestSuite suite = new TestSuite();
|
||||
// return suite;
|
||||
//}
|
||||
}// end LoginITest
|
||||
// This is a test suite that runs LoginTest and ValidateTest
|
||||
}
|
||||
@ -0,0 +1,93 @@
|
||||
package com.atm.dao;
|
||||
|
||||
import com.atm.controller.Validate;
|
||||
import com.atm.model.Customer;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.MockedStatic;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
public class LoginIntegratedTestNew {
|
||||
|
||||
@Mock
|
||||
private ResultSet mockResultSet;
|
||||
|
||||
private Login login;
|
||||
private Customer testCustomer;
|
||||
|
||||
@BeforeEach
|
||||
public void setUp() {
|
||||
login = new Login();
|
||||
testCustomer = new Customer();
|
||||
testCustomer.setCid(123456L);
|
||||
testCustomer.setCpin("123456");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testLoginAndValidateIntegration() throws SQLException {
|
||||
// 使用Mockito模拟静态方法DbUtil.executeQuery
|
||||
try (MockedStatic<DbUtil> mockedDbUtil = mockStatic(DbUtil.class)) {
|
||||
// 模拟数据库返回有效用户
|
||||
mockedDbUtil.when(() -> DbUtil.executeQuery(anyString())).thenReturn(mockResultSet);
|
||||
when(mockResultSet.next()).thenReturn(true);
|
||||
when(mockResultSet.getString("cid")).thenReturn("123456");
|
||||
when(mockResultSet.getString("cpin")).thenReturn("123456");
|
||||
when(mockResultSet.getString("cname")).thenReturn("测试用户");
|
||||
|
||||
// 测试登录功能
|
||||
boolean loginResult = login.login(testCustomer);
|
||||
assertTrue(loginResult, "登录应该成功");
|
||||
|
||||
// 验证DbUtil.executeQuery被调用
|
||||
mockedDbUtil.verify(() -> DbUtil.executeQuery("select * from customer"));
|
||||
|
||||
// 验证ResultSet的方法被调用
|
||||
verify(mockResultSet).next();
|
||||
verify(mockResultSet).getString("cid");
|
||||
verify(mockResultSet).getString("cpin");
|
||||
verify(mockResultSet).getString("cname");
|
||||
}
|
||||
|
||||
// 测试验证功能
|
||||
assertTrue(Validate.isNumeric("123456"), "123456应该是数字");
|
||||
assertTrue(Validate.lengthValidate("123456"), "123456长度应该是6位");
|
||||
|
||||
assertFalse(Validate.isNumeric("abc123"), "abc123不应该是纯数字");
|
||||
assertFalse(Validate.lengthValidate("123"), "123长度不应该是6位");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testLoginFailedAndValidateIntegration() throws SQLException {
|
||||
// 使用Mockito模拟静态方法DbUtil.executeQuery
|
||||
try (MockedStatic<DbUtil> mockedDbUtil = mockStatic(DbUtil.class)) {
|
||||
// 模拟数据库返回无效用户
|
||||
mockedDbUtil.when(() -> DbUtil.executeQuery(anyString())).thenReturn(mockResultSet);
|
||||
when(mockResultSet.next()).thenReturn(false);
|
||||
|
||||
// 测试登录失败
|
||||
boolean loginResult = login.login(testCustomer);
|
||||
assertFalse(loginResult, "登录应该失败");
|
||||
|
||||
// 验证DbUtil.executeQuery被调用
|
||||
mockedDbUtil.verify(() -> DbUtil.executeQuery("select * from customer"));
|
||||
|
||||
// 验证ResultSet的方法被调用
|
||||
verify(mockResultSet).next();
|
||||
}
|
||||
|
||||
// 测试验证功能
|
||||
assertFalse(Validate.isNumeric("wrongpin"), "wrongpin不应该是纯数字");
|
||||
assertFalse(Validate.lengthValidate("wrongpin"), "wrongpin长度不应该是6位");
|
||||
}
|
||||
}
|
||||
@ -1,49 +1,70 @@
|
||||
package com.atm.dao;
|
||||
|
||||
import org.junit.Assert;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
import com.atm.dao.Login;
|
||||
import com.atm.model.Customer;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.MockedStatic;
|
||||
import org.mockito.Mockito;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
public class LoginTest extends junit.framework.TestCase {
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
|
||||
/**
|
||||
*
|
||||
* @param arg0
|
||||
*/
|
||||
public LoginTest(String arg0) {
|
||||
super(arg0);
|
||||
}
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
/**
|
||||
*
|
||||
* @param args
|
||||
*/
|
||||
public static void main(String[] args) {
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
public class LoginTest {
|
||||
|
||||
}
|
||||
@InjectMocks
|
||||
private Login login;
|
||||
|
||||
/**
|
||||
*
|
||||
* @exception Exception
|
||||
*/
|
||||
protected void setUp()
|
||||
throws Exception {
|
||||
super.setUp();
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @exception Exception
|
||||
*/
|
||||
protected void tearDown()
|
||||
throws Exception {
|
||||
super.tearDown();
|
||||
}
|
||||
public final void testLogin() {
|
||||
Assert.assertTrue(new Login().login(new Customer("123456", "123456")));
|
||||
}
|
||||
public final void testLogin_failed() {
|
||||
Assert.assertFalse(new Login().login(new Customer("123457", "123458")));
|
||||
}
|
||||
}// end LoginTest
|
||||
@Test
|
||||
public void testLogin() throws SQLException {
|
||||
try (MockedStatic<DbUtil> dbUtilMock = Mockito.mockStatic(DbUtil.class)) {
|
||||
// Mock ResultSet
|
||||
ResultSet mockResultSet = mock(ResultSet.class);
|
||||
when(mockResultSet.next()).thenReturn(true, false); // First call returns true, second returns false
|
||||
when(mockResultSet.getString("cid")).thenReturn("123456");
|
||||
when(mockResultSet.getString("cpin")).thenReturn("123456");
|
||||
when(mockResultSet.getString("cname")).thenReturn("张三");
|
||||
|
||||
// Mock DbUtil.executeQuery to return our mock ResultSet
|
||||
dbUtilMock.when(() -> DbUtil.executeQuery(anyString())).thenReturn(mockResultSet);
|
||||
|
||||
// Create customer with matching credentials
|
||||
Customer customer = new Customer();
|
||||
customer.setCid(123456L);
|
||||
customer.setCpin("123456");
|
||||
|
||||
// Test login
|
||||
assertTrue(login.login(customer));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testLogin_failed() throws SQLException {
|
||||
try (MockedStatic<DbUtil> dbUtilMock = Mockito.mockStatic(DbUtil.class)) {
|
||||
// Mock ResultSet with no matching records
|
||||
ResultSet mockResultSet = mock(ResultSet.class);
|
||||
when(mockResultSet.next()).thenReturn(false); // No records found
|
||||
|
||||
// Mock DbUtil.executeQuery to return our mock ResultSet
|
||||
dbUtilMock.when(() -> DbUtil.executeQuery(anyString())).thenReturn(mockResultSet);
|
||||
|
||||
// Create customer with non-matching credentials
|
||||
Customer customer = new Customer();
|
||||
customer.setCid(123457L);
|
||||
customer.setCpin("123458");
|
||||
|
||||
// Test login
|
||||
assertFalse(login.login(customer));
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,226 @@
|
||||
package com.atm.service;
|
||||
|
||||
import com.atm.config.JwtTokenUtil;
|
||||
import com.atm.model.Customer;
|
||||
import com.atm.repository.CustomerRepository;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.security.authentication.AuthenticationManager;
|
||||
import org.springframework.security.authentication.BadCredentialsException;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
public class AuthenticationServiceTest {
|
||||
|
||||
@Mock
|
||||
private AuthenticationManager authenticationManager;
|
||||
|
||||
@Mock
|
||||
private JwtTokenUtil jwtTokenUtil;
|
||||
|
||||
@Mock
|
||||
private CustomerService customerService;
|
||||
|
||||
@Mock
|
||||
private Authentication authentication;
|
||||
|
||||
@Mock
|
||||
private UserDetails userDetails;
|
||||
|
||||
@InjectMocks
|
||||
private AuthenticationService authenticationService;
|
||||
|
||||
private Customer testCustomer;
|
||||
|
||||
@BeforeEach
|
||||
public void setUp() {
|
||||
testCustomer = new Customer();
|
||||
testCustomer.setCid(12345L);
|
||||
testCustomer.setCname("测试用户");
|
||||
testCustomer.setCpin("123456");
|
||||
testCustomer.setCstatus("active");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAuthenticateAndGenerateToken_Success() {
|
||||
// Given
|
||||
Long cid = 12345L;
|
||||
String cpin = "123456";
|
||||
String expectedToken = "jwt.token.here";
|
||||
|
||||
when(authenticationManager.authenticate(any(UsernamePasswordAuthenticationToken.class)))
|
||||
.thenReturn(authentication);
|
||||
when(authentication.isAuthenticated()).thenReturn(true);
|
||||
when(authentication.getPrincipal()).thenReturn(userDetails);
|
||||
when(jwtTokenUtil.generateToken(userDetails)).thenReturn(expectedToken);
|
||||
|
||||
// When
|
||||
Optional<String> result = authenticationService.authenticateAndGenerateToken(cid, cpin);
|
||||
|
||||
// Then
|
||||
assertTrue(result.isPresent());
|
||||
assertEquals(expectedToken, result.get());
|
||||
verify(authenticationManager).authenticate(any(UsernamePasswordAuthenticationToken.class));
|
||||
verify(jwtTokenUtil).generateToken(userDetails);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAuthenticateAndGenerateToken_BadCredentials() {
|
||||
// Given
|
||||
Long cid = 12345L;
|
||||
String cpin = "wrongpin";
|
||||
|
||||
when(authenticationManager.authenticate(any(UsernamePasswordAuthenticationToken.class)))
|
||||
.thenThrow(new BadCredentialsException("认证失败"));
|
||||
|
||||
// When
|
||||
Optional<String> result = authenticationService.authenticateAndGenerateToken(cid, cpin);
|
||||
|
||||
// Then
|
||||
assertFalse(result.isPresent());
|
||||
verify(authenticationManager).authenticate(any(UsernamePasswordAuthenticationToken.class));
|
||||
verify(jwtTokenUtil, never()).generateToken(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAuthenticateAndGenerateToken_NotAuthenticated() {
|
||||
// Given
|
||||
Long cid = 12345L;
|
||||
String cpin = "123456";
|
||||
|
||||
when(authenticationManager.authenticate(any(UsernamePasswordAuthenticationToken.class)))
|
||||
.thenReturn(authentication);
|
||||
when(authentication.isAuthenticated()).thenReturn(false);
|
||||
|
||||
// When
|
||||
Optional<String> result = authenticationService.authenticateAndGenerateToken(cid, cpin);
|
||||
|
||||
// Then
|
||||
assertFalse(result.isPresent());
|
||||
verify(authenticationManager).authenticate(any(UsernamePasswordAuthenticationToken.class));
|
||||
verify(jwtTokenUtil, never()).generateToken(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testValidateToken_ValidToken() {
|
||||
// Given
|
||||
String token = "valid.jwt.token";
|
||||
String username = "12345";
|
||||
|
||||
when(jwtTokenUtil.getUsernameFromToken(token)).thenReturn(username);
|
||||
when(customerService.loadUserByUsername(username)).thenReturn(userDetails);
|
||||
when(jwtTokenUtil.validateToken(token, userDetails)).thenReturn(true);
|
||||
|
||||
// When
|
||||
boolean result = authenticationService.validateToken(token);
|
||||
|
||||
// Then
|
||||
assertTrue(result);
|
||||
verify(jwtTokenUtil).getUsernameFromToken(token);
|
||||
verify(customerService).loadUserByUsername(username);
|
||||
verify(jwtTokenUtil).validateToken(token, userDetails);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testValidateToken_InvalidToken() {
|
||||
// Given
|
||||
String token = "invalid.jwt.token";
|
||||
|
||||
when(jwtTokenUtil.getUsernameFromToken(token)).thenThrow(new RuntimeException("Invalid token"));
|
||||
|
||||
// When
|
||||
boolean result = authenticationService.validateToken(token);
|
||||
|
||||
// Then
|
||||
assertFalse(result);
|
||||
verify(jwtTokenUtil).getUsernameFromToken(token);
|
||||
verify(customerService, never()).loadUserByUsername(anyString());
|
||||
verify(jwtTokenUtil, never()).validateToken(any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetUsernameFromToken_ValidToken() {
|
||||
// Given
|
||||
String token = "valid.jwt.token";
|
||||
String expectedUsername = "12345";
|
||||
|
||||
when(jwtTokenUtil.getUsernameFromToken(token)).thenReturn(expectedUsername);
|
||||
|
||||
// When
|
||||
String result = authenticationService.getUsernameFromToken(token);
|
||||
|
||||
// Then
|
||||
assertEquals(expectedUsername, result);
|
||||
verify(jwtTokenUtil).getUsernameFromToken(token);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetUsernameFromToken_InvalidToken() {
|
||||
// Given
|
||||
String token = "invalid.jwt.token";
|
||||
|
||||
when(jwtTokenUtil.getUsernameFromToken(token)).thenThrow(new RuntimeException("Invalid token"));
|
||||
|
||||
// When
|
||||
String result = authenticationService.getUsernameFromToken(token);
|
||||
|
||||
// Then
|
||||
assertNull(result);
|
||||
verify(jwtTokenUtil).getUsernameFromToken(token);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRefreshToken_ValidToken() {
|
||||
// Given
|
||||
String oldToken = "valid.jwt.token";
|
||||
String newToken = "new.jwt.token";
|
||||
String username = "12345";
|
||||
|
||||
when(jwtTokenUtil.getUsernameFromToken(oldToken)).thenReturn(username);
|
||||
when(customerService.loadUserByUsername(username)).thenReturn(userDetails);
|
||||
when(jwtTokenUtil.validateToken(oldToken, userDetails)).thenReturn(true);
|
||||
when(jwtTokenUtil.generateToken(userDetails)).thenReturn(newToken);
|
||||
|
||||
// When
|
||||
Optional<String> result = authenticationService.refreshToken(oldToken);
|
||||
|
||||
// Then
|
||||
assertTrue(result.isPresent());
|
||||
assertEquals(newToken, result.get());
|
||||
verify(jwtTokenUtil).getUsernameFromToken(oldToken);
|
||||
verify(customerService).loadUserByUsername(username);
|
||||
verify(jwtTokenUtil).validateToken(oldToken, userDetails);
|
||||
verify(jwtTokenUtil).generateToken(userDetails);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRefreshToken_InvalidToken() {
|
||||
// Given
|
||||
String invalidToken = "invalid.token.here";
|
||||
|
||||
when(jwtTokenUtil.getUsernameFromToken(invalidToken)).thenThrow(new RuntimeException("Invalid token"));
|
||||
|
||||
// When
|
||||
Optional<String> result = authenticationService.refreshToken(invalidToken);
|
||||
|
||||
// Then
|
||||
assertFalse(result.isPresent());
|
||||
verify(jwtTokenUtil).getUsernameFromToken(invalidToken);
|
||||
verify(customerService, never()).loadUserByUsername(anyString());
|
||||
verify(jwtTokenUtil, never()).validateToken(any(), any());
|
||||
verify(jwtTokenUtil, never()).generateToken(any());
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,118 @@
|
||||
package com.atm.system;
|
||||
|
||||
import com.atm.controller.AuthController;
|
||||
import com.atm.service.AuthenticationService;
|
||||
import com.atm.service.CustomerService;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
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.WebMvcTest;
|
||||
import org.springframework.boot.test.mock.mockito.MockBean;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.security.authentication.AuthenticationManager;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.test.context.ActiveProfiles;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
|
||||
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.when;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
|
||||
|
||||
/**
|
||||
* 测试登录功能的完整流程
|
||||
*/
|
||||
@WebMvcTest(AuthController.class)
|
||||
@ActiveProfiles("test")
|
||||
public class LoginSystemTest {
|
||||
|
||||
@Autowired
|
||||
private MockMvc mockMvc;
|
||||
|
||||
@Autowired
|
||||
private ObjectMapper objectMapper;
|
||||
|
||||
@MockBean
|
||||
private AuthenticationService authenticationService;
|
||||
|
||||
@MockBean
|
||||
private CustomerService customerService;
|
||||
|
||||
@MockBean
|
||||
private AuthenticationManager authenticationManager;
|
||||
|
||||
@MockBean
|
||||
private com.atm.config.JwtTokenUtil jwtTokenUtil;
|
||||
|
||||
@MockBean
|
||||
private org.springframework.security.core.userdetails.UserDetailsService userDetailsService;
|
||||
|
||||
@MockBean
|
||||
private PasswordEncoder passwordEncoder;
|
||||
|
||||
private Map<String, Object> loginRequest;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
loginRequest = new HashMap<>();
|
||||
loginRequest.put("cid", 12345L);
|
||||
loginRequest.put("cpin", "123456");
|
||||
}
|
||||
|
||||
@Test
|
||||
void testLoginSuccessSystemFlow() throws Exception {
|
||||
// 模拟认证成功
|
||||
when(authenticationService.authenticateAndGenerateToken(any(), anyString()))
|
||||
.thenReturn(java.util.Optional.of("mock-jwt-token"));
|
||||
|
||||
mockMvc.perform(MockMvcRequestBuilders.post("/api/auth/login")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(loginRequest)))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.token").value("mock-jwt-token"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testLoginFailureSystemFlow() throws Exception {
|
||||
// 模拟认证失败
|
||||
when(authenticationService.authenticateAndGenerateToken(any(), anyString()))
|
||||
.thenReturn(java.util.Optional.empty());
|
||||
|
||||
mockMvc.perform(MockMvcRequestBuilders.post("/api/auth/login")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(loginRequest)))
|
||||
.andExpect(status().isUnauthorized());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testLoginWithWrongPinSystemFlow() throws Exception {
|
||||
// 设置错误的PIN码
|
||||
loginRequest.put("cpin", "wrongpin");
|
||||
|
||||
// 模拟认证失败
|
||||
when(authenticationService.authenticateAndGenerateToken(any(), anyString()))
|
||||
.thenReturn(java.util.Optional.empty());
|
||||
|
||||
mockMvc.perform(MockMvcRequestBuilders.post("/api/auth/login")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(loginRequest)))
|
||||
.andExpect(status().isUnauthorized());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testLoginWithInvalidCidFormatSystemFlow() throws Exception {
|
||||
// 设置无效的客户ID格式
|
||||
loginRequest.put("cid", "invalid-cid");
|
||||
|
||||
mockMvc.perform(MockMvcRequestBuilders.post("/api/auth/login")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(loginRequest)))
|
||||
.andExpect(status().isBadRequest());
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,91 @@
|
||||
package com.atm.system;
|
||||
|
||||
import com.atm.controller.AuthController;
|
||||
import com.atm.service.AuthenticationService;
|
||||
import com.atm.service.CustomerService;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
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.AutoConfigureWebMvc;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.test.mock.mockito.MockBean;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.security.authentication.AuthenticationManager;
|
||||
import org.springframework.security.test.context.support.WithMockUser;
|
||||
import org.springframework.test.context.ActiveProfiles;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||
import org.springframework.web.context.WebApplicationContext;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.when;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
|
||||
|
||||
/**
|
||||
* 简化的登录系统测试
|
||||
*/
|
||||
@SpringBootTest
|
||||
@AutoConfigureWebMvc
|
||||
@ActiveProfiles("test")
|
||||
public class SimpleLoginSystemTest {
|
||||
|
||||
@Autowired
|
||||
private WebApplicationContext webApplicationContext;
|
||||
|
||||
@Autowired
|
||||
private ObjectMapper objectMapper;
|
||||
|
||||
@MockBean
|
||||
private AuthenticationService authenticationService;
|
||||
|
||||
@MockBean
|
||||
private CustomerService customerService;
|
||||
|
||||
@MockBean
|
||||
private AuthenticationManager authenticationManager;
|
||||
|
||||
private MockMvc mockMvc;
|
||||
private Map<String, Object> loginRequest;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
|
||||
loginRequest = new HashMap<>();
|
||||
loginRequest.put("cid", 12345L);
|
||||
loginRequest.put("cpin", "123456");
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithMockUser
|
||||
void testLoginSuccessSystemFlow() throws Exception {
|
||||
// 模拟认证成功
|
||||
when(authenticationService.authenticateAndGenerateToken(12345L, "123456"))
|
||||
.thenReturn(java.util.Optional.of("mock-jwt-token"));
|
||||
|
||||
mockMvc.perform(post("/api/auth/login")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(loginRequest)))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.token").value("mock-jwt-token"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithMockUser
|
||||
void testLoginFailureSystemFlow() throws Exception {
|
||||
// 模拟认证失败
|
||||
when(authenticationService.authenticateAndGenerateToken(12345L, "123456"))
|
||||
.thenReturn(java.util.Optional.empty());
|
||||
|
||||
mockMvc.perform(post("/api/auth/login")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(loginRequest)))
|
||||
.andExpect(status().isUnauthorized());
|
||||
}
|
||||
}
|
||||
Loading…
Reference in new issue