Search code examples
javaspring-bootjunit5

SpringBootTest mockMvc returns 404 instead of 200


I'm testing some end points. They are return what's is supposed to if i hit in bowser.

enter image description here

So, i building tests for them.

@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]'}]"));
}

but when execute this test, it's return this:

enter image description here

I don't know why this is. Someone could help me?

There the controller and repository classes:

This is my controller:

@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();
}

This is my service class

@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);
}

This is my repository

@Repository
public interface UserRepository  {

UserEntity findById(int id);
List<UserEntity> findAll();
UserEntity save(UserEntity user);
void delete(int id);
}

Solution

  • looks like /api is context path and you don't need to have context path in mockMvc.perform(get("/api/user")), remove the context path as below should work

    mockMvc.perform(get("/user"))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON))
            .andExpect(content().json("[{'id': 1, 'name': 'Alice', 'email': '[email protected]'}]"));