代码之家  ›  专栏  ›  技术社区  ›  dcm50

JUnit 5-已创建但未检索的实体

  •  0
  • dcm50  · 技术社区  · 3 年前

    我正在测试服务类中的一个方法,该方法基本上调用 save 从我的存储库类:

    @Repository
    public interface GameManagerRepository extends JpaRepository<Game, String> {
    
        Game findCreateGameByPublisherId(String publisherId);
    }
    

    这是我的测试方法:

        @DisplayName("Test for createGame")
        @Test
        public void createGameTest(){
            game = new Game();
            game.setPublisherId("123");
            game.setGameDataId("abc");
            game.setName("hello world");
            gameManagerRepository.save(game);
            System.out.println(game);
            System.out.println(game != null);
            System.out.println(gameManagerRepository.findCreateGameByPublisherId("123"));
        }
    

    我确实放了一些 System.out.println 试图确定我的代码到底出了什么问题,结果是:

    Game(gameDataId=abc, publisherId=123, name=hello world, timePlayed=null)
    true
    null
    

    正如你所看到的,我在数据库中找不到实体,也找不到原因。
    我在这里做错了什么?

    0 回复  |  直到 3 年前
        1
  •  0
  •   daniu    3 年前

    既然你在你使用的评论中声明 MockitoExtension 但不要具体说明您是如何创建存储库的,我将不得不假设您是这样做的:

    @ExtendWith(MockitoExtension.class)
    public class RepositoryTest {
    
        @Mock
        private GameManagerRepository gameManagerRepository;
    
        @DisplayName("Test for createGame")
        @Test
        public void createGameTest(){
            game = new Game();
            game.setPublisherId("123");
            game.setGameDataId("abc");
            game.setName("hello world");
            gameManagerRepository.save(game);
            System.out.println(game);
            System.out.println(game != null);
            System.out.println(gameManagerRepository.findCreateGameByPublisherId("123"));
        }
    }
    

    答案是对模拟实例的方法调用总是返回 null 如果你事先不嘲笑那通电话(如 when(repo.findCreate(any())).thenReturn(game) )。

    这个答案是正确的,但有点开玩笑地告诉你为什么展示如何创建存储库很重要。

    您可能想要创建一个Spring测试( @ExtendsWith(SpringExtension.class) )以启动Spring上下文并测试实际的bean。