SpringBootTest mockMvc返回404而不是200
问题描述
我正在测试一些端点。如果我在浏览器中访问它们,它们会返回预期结果。
因此,我正在为它们构建测试。
@SpringBootTest
@AutoConfigureMockMvc
public class UserControllerTest {
@Autowired
private MockMvc mockMvc;
@Autowired
private WebApplicationContext webApplicationContext;
@MockBean
private UserRepository userRepository;
private List<UserEntity> sampleUsers;
@BeforeEach
public void setUp() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.webApplicationContext).dispatchOptions(true).build();
this.sampleUsers = Arrays.asList(
new UserEntity(1, "Alice", "[email protected]", "alicePassword"),
new UserEntity(2, "Bob", "[email protected]", "bobPassword")
);
}
@Test
public void getAllUsers_shouldReturnUsers() throws Exception {
given(userRepository.findAll()).willReturn(sampleUsers);
mockMvc.perform(get("/api/user"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(content().json("[{'id': 1, 'name': 'Alice', 'email': '[email protected]'}]"));
}
但当执行这个测试时,返回的是这个:
我不知道为什么会这样。有人可以帮我吗?
这是控制器和存储库类:
这是我的控制器:
@RestController
@RequestMapping("/user")
@Api(value = "User Management System")
public class UserController {
@Autowired
private UserRepository userRepository;
@ApiOperation(value = "Get a user by Id", response = UserEntity.class)
@GetMapping("/{id}")
public ResponseEntity<UserEntity> getUserById(@PathVariable int id) {
UserEntity user = userRepository.findById(id);
if(user != null) {
return ResponseEntity.ok(user);
} else {
return ResponseEntity.notFound().build();
}
}
@ApiOperation(value = "Get all users", response = List.class)
@GetMapping
public List<UserEntity> getAllUsers() {
return userRepository.findAll();
}
这是我的服务类
@Service
public class UserRepositoryImpl implements UserRepository {
@Autowired
private DSLContext dsl;
@Override
public UserEntity findById(int id) {
UsersRecord record = dsl.selectFrom(USERS)
.where(USERS.ID.eq(id))
.fetchOne();
if (record != null) {
return record.into(UserEntity.class);
}
return null;
}
@Override
public List<UserEntity> findAll() {
return dsl.selectFrom(USERS).fetchInto(UserEntity.class);
}
这是我的存储库
@Repository
public interface UserRepository {
UserEntity findById(int id);
List<UserEntity> findAll();
UserEntity save(UserEntity user);
void delete(int id);
}
解决方案
看起来/api
是上下文路径,你不需要在mockMvc.perform(get("/api/user"))
中包含上下文路径,移除上下文路径,以下方式应该可行。
mockMvc.perform(get("/user"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(content().json("[{'id': 1, 'name': 'Alice', 'email': '[email protected]'}]"));