mockbean时动态生成数据

@Bean
    public IdGeneratorService idGeneratorService(){
        IdGeneratorService idGeneratorService = Mockito.mock(IdGeneratorService.class);
        // 返回一个结果集
//        Mockito.when(idGeneratorService.nextId()).thenReturn(1l,2l,3l,4l,5l,6l,7l,8l,9l,10l,11l,12l,13l,14l,15l,16l,17l,18l);
        // 动态返回结果
        Mockito.when(idGeneratorService.nextId()).thenAnswer((Answer<Long>) invocation -> id++);
        // 根据入参动态返回结果
        Mockito.when(idGeneratorService.nextIds(Mockito.anyInt())).thenAnswer((Answer<List<Long>>) invocation -> {
            List<Long> ids = Lists.newArrayList();
            int arg = invocation.getArgument(0);
            for (int i = 0; i < arg;i++) {
                ids.add(id++);
            }
            return ids;
        });

        return idGeneratorService;
    }

  

posted on 2021-06-02 10:07  永不宕机  阅读(166)  评论(0编辑  收藏  举报

导航