MockMVC 在我的存储库中带有 @Query 或重构我的控制器以不使用它?

MockMVC with a @Query in my Repository or refactor my controller to not use it?

我的存储库中有一个 @Query,我根据 SQL 查询 return 数据到我的控制器,我将如何模拟它?

这是我的存储库

package movieweb.movies.repository;

import movieweb.movies.models.UserMovies;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface UserMoviesRepository extends CrudRepository<UserMovies, Integer> {

    @Query(value = "select * from movies, user_movies where movies.movie_id = user_movies.movie_id and uname = ?1", nativeQuery = true)
    List<UserMovies> findByUname(String uname);
}

这是我的控制器

package movieweb.movies.controllers;

import movieweb.movies.models.Movies;
import movieweb.movies.models.UserMovies;
import movieweb.movies.repository.UserMoviesRepository;
import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.Query;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class UserMoviesController {

    @Autowired
    private UserMoviesRepository umRepository;

    @CrossOrigin
    @PostMapping(path = "/newUserMovie")
    public ResponseEntity<UserMovies> addNewUserMovie(@RequestBody UserMovies data){
          umRepository.save(data);
        return new ResponseEntity<UserMovies>(data, HttpStatus.CREATED);

    }

    @CrossOrigin
    @GetMapping(path="/getUserMovies")
    public  List<UserMovies> getUsersMovies(){
        return (List<UserMovies>) umRepository.findAll();
    }

    @CrossOrigin
    @GetMapping(path = "/getUserMovies/{uname}")
    public  List<UserMovies> getUserMovies(@PathVariable String uname){
        return umRepository.findByUname(uname);
    }

    @CrossOrigin
    @DeleteMapping(path ="/deleteUserMovies/{id}")
    ResponseEntity deleteUserMovie(@PathVariable Integer id) {
        umRepository.deleteById(id);
        return new ResponseEntity(HttpStatus.ACCEPTED);
    }

    @CrossOrigin
    @PutMapping("/usermovie/update/{id}")
    public ResponseEntity<UserMovies> updateMovie(@RequestBody UserMovies updateMovie, @PathVariable Integer id) {
       return umRepository.findById(id)
                .map(userMovies -> {
                    userMovies.setMovieId(updateMovie.getMovieId());
                    userMovies.setUname(updateMovie.getUname());
                     umRepository.save(userMovies);
                    return new ResponseEntity<UserMovies>(userMovies, HttpStatus.OK);

                })
                .orElseGet(() -> {
                    updateMovie.setMovieId(id);
                     umRepository.save(updateMovie);
                    return new ResponseEntity<UserMovies>(updateMovie, HttpStatus.OK);
                });
    }

}

这是我在测试中尝试做的事情

@Test
    void getUserMoviesPerUser() throws Exception{
        ArrayList<UserMovies> userMovies = new ArrayList<>();
        userMovies.add(new UserMovies(1, "jamie", 1));
        userMovies.add(new UserMovies(2, "joe", 1));
        userMovies.add(new UserMovies(3, "jamie", 2));
        userMovies.add(new UserMovies(4, "joe", 2));

        when(userMoviesRepository.findByUname("jamie")).thenReturn(userMovies);
        mockMvc.perform(get("/getUserMovies/{uname}", "jamie"))
                .andDo(print())
                .andExpect(jsonPath("$", hasSize(2)))
                .andExpect(jsonPath("$[0].userMovieID", is(1)))
                .andExpect(jsonPath("$[0].uname", is("jamie")))
                .andExpect(jsonPath("$[0].movieId", is(1)))
                .andExpect(jsonPath("$[1].userMovieID", is(3)))
                .andExpect(jsonPath("$[1].uname", is("jamie")))
                .andExpect(jsonPath("$[1].movieId", is(1)));

        Mockito.verify(userMoviesRepository, times(1)).findAll();
    }

我面临的问题是,当我 运行 上面的测试时,我没有像我期望的那样只返回 2 条记录,而是返回 4 条记录。这是有道理的,因为我不能依赖SQL 到 运行 测试。有没有更好的方法来编写我的控制器以获取基于 movie_id 的数据?

我认为您需要 return 您期望的唯一记录。喜欢

@Test
    void getUserMoviesPerUser() throws Exception{
        ArrayList<UserMovies> userMovies = new ArrayList<>();
        userMovies.add(new UserMovies(1, "jamie", 1));
        userMovies.add(new UserMovies(3, "jamie", 2));

        when(userMoviesRepository.findByUname("jamie")).thenReturn(userMovies);
        mockMvc.perform(get("/getUserMovies/{uname}", "jamie"))
                .andDo(print())
                .andExpect(jsonPath("$", hasSize(2)))
                .andExpect(jsonPath("$[0].userMovieID", is(1)))
                .andExpect(jsonPath("$[0].uname", is("jamie")))
                .andExpect(jsonPath("$[0].movieId", is(1)))
                .andExpect(jsonPath("$[1].userMovieID", is(3)))
                .andExpect(jsonPath("$[1].uname", is("jamie")))
                .andExpect(jsonPath("$[1].movieId", is(1)));

        Mockito.verify(userMoviesRepository, times(1)).findAll();
    }

在您的代码中,您正在创建 4 records 用于模拟,然后只需删除 2 of them 以便您将 2 records 作为响应。

@Test
void getUserMoviesPerUser() throws Exception{
    ArrayList<UserMovies> userMovies = new ArrayList<>();
    userMovies.add(new UserMovies(1, "jamie", 1));
    userMovies.add(new UserMovies(2, "joe", 1));

    when(userMoviesRepository.findByUname("jamie")).thenReturn(userMovies);
    mockMvc.perform(get("/getUserMovies/{uname}", "jamie"))
            .andDo(print())
            .andExpect(jsonPath("$", hasSize(2)))
            .andExpect(jsonPath("$[0].userMovieID", is(1)))
            .andExpect(jsonPath("$[0].uname", is("jamie")))
            .andExpect(jsonPath("$[0].movieId", is(1)))
            .andExpect(jsonPath("$[1].userMovieID", is(3)))
            .andExpect(jsonPath("$[1].uname", is("jamie")))
            .andExpect(jsonPath("$[1].movieId", is(1)));

    Mockito.verify(userMoviesRepository, times(1)).findAll();
}