我在运行 Spring Boot 项目测试时收到 404 Not Found 错误。看来我的代码没有正确模拟 URL。我刚开始将mockito 与Spring 框架一起使用。任何帮助将不胜感激。
这是我的代码-
UserController.java
@RestController
public class UserInfoController {
@Autowired
private UserInfoService userInfoService;
@GetMapping("/userDetail")
public ResponseEntity<?> getUserDetail(@RequestParam("user") String user) {
return userService.getUserDetails(user);
}
}
UserInfo.java
private String user;
private String workstation;
private String status;
private String message;
public UserInfo() {
}
public UserInfo(String user, String workstation) {
super();
this.user = user;
this.workstation = workstation;
this.status = "Success";
this.message = "User exists in database and has access to given workstation";
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getWorkstation() {
return workstation;
}
public void setWorkstation(String workstation) {
this.workstation = workstation;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
应用程序属性
users.admin=abc
users.staff=abc
app2Url=http://localhost:8080/app2
ConfigSecurity.java
@org.springframework.context.annotation.Configuration
public class ConfigSecurity extends WebSecurityConfiguration{
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/userDetail").authenticated())
.httpBasic(Customizer.withDefaults());
}
public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
return httpSecurity
.csrf(csrf -> csrf.disable())
.authorizeHttpRequests(auth -> auth
.anyRequest().authenticated()
)
.sessionManagement(sess -> sess.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.httpBasic(Customizer.withDefaults())
.build();
}
}
UserService.java
@Service
public class UserService {
@Value("#{${users}}")
private Map<String, String> userInfoProperties;
@Value("${appName2Url}")
private String appName2Url;
private final RestTemplate restTemplate = new RestTemplate();
public ResponseEntity<?> getUserDetails(String user) {
if (userInfoProperties.containsKey(user)) {
String workstation = userInfoProperties.get(user);
String url = appName2Url + "/addUserInfo";
UserInfo userInfo = new UserInfo(user, workstation);
ResponseEntity<UserInfo> response = restTemplate.postForEntity(url, userInfo, UserInfo.class);
return new ResponseEntity<>(response.getBody(), HttpStatus.OK);
} else {
return new ResponseEntity<>("User not found", HttpStatus.NOT_FOUND);
}
}
public void setUserInfoProperties(Map<String, String> userInfoProperties) {
this.userInfoProperties = userInfoProperties;
}
public void setAppName2Url(String appName2Url) {
this.appName2Url = appName2Url;
}
}
UserInfoServiceTest.java
@ExtendWith(MockitoExtension.class)
公共类 UserServiceTest {
@Mock
private RestTemplate restTemplate;
@InjectMocks
private UserService userService;
@BeforeEach
public void setUp() {
// Initialize the userInfoProperties map manually
Map<String, String> userInfoProperties = new HashMap<>();
userInfoProperties.put("admin", "CCUICKB0F1");
userService.setUserInfoProperties(userInfoProperties);
// Set the appName2Url manually
userService.setAppName2Url("http://localhost:8080/appName2");
}
@Test
public void testGetUserDetails_UserExists() {
// Set up test data
UserInfo mockUserInfo = new UserInfo("admin", "CCUICKB0F1");
ResponseEntity<UserInfo> mockResponse = new ResponseEntity<>(mockUserInfo, HttpStatus.OK);
// Mock external service call
when(restTemplate.postForEntity(eq("http://localhost:8080/appName2/addUserInfo"), any(UserInfo.class), eq(UserInfo.class)))
.thenReturn(mockResponse);
// Execute the method to be tested
ResponseEntity<?> response = userService.getUserDetails("admin");
// Verify the response
assert(response.getStatusCode() == HttpStatus.OK);
assert(response.getBody().equals(mockUserInfo));
}
@Test
public void testGetUserDetails_UserNotFound() {
// Set up test data for non-existing user
Map<String, String> userInfoProperties = new HashMap<>();
userService.setUserInfoProperties(userInfoProperties);
// Set the appName2Url manually
userService.setAppName2Url("http://localhost:8080/appName2");
// Execute the method to be tested
ResponseEntity<?> response = userService.getUserDetails("admin");
// Verify the response
assert(response.getStatusCode() == HttpStatus.NOT_FOUND);
assert(response.getBody().equals("User not found"));
}
}
代码运行并测试给出错误 404 Not Found。如果有人可以帮忙解决这个问题。这真的很有帮助。谢谢!
当然会是 404 - 你的应用程序没有运行。
@ExtendWith(MockitoExtension.class)
仅启用 Mockito - 不启用 Spring 容器或服务器。
你可以使用
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class UserServiceTest {
启动服务器。阅读一下https://spring.io/guides/gs/testing-web