SpringBootTest mockMvc 返回 404 而不是 200

问题描述 投票:0回答:1

我正在测试一些终点。如果我击中了鲍泽,他们会返回应有的结果。

所以,我为他们构建测试。

@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);
}
java spring-boot junit5
1个回答
0
投票

看起来

/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]'}]"));
© www.soinside.com 2019 - 2024. All rights reserved.