当前位置: 首页 > 知识库问答 >
问题:

模拟给出错误的服务类方法

凤自珍
2023-03-14

我是新的mockito和jUnit我不明白为什么我得到错误和如何模仿这个服务类方法

请帮我解决这个问题。是否需要模拟可分页和切片对象。为什么在嘲笑PartnerEventRepository之后,我也会说

“需要但未调用:partnerEventRepository.findAll(Cassandra页面请求[编号:0,大小5,排序:未排序,分页状态:null])

@Service
public class PartnerIndexServiceImpl implements PartnerIndexService {


    private Logger logger = LoggerFactory.getLogger(this.getClass());


    private EventHandler<Event<Entity>, Index> indexEventHandler;
    private PartnerProjectionQueryRepository queryRepository;
    private PartnerEventRepository partnerEventRepository;
    private MessageSource msgSource;


    @Autowired
    private GlobalPartnerProjectionQueryRepository globalPartnerQueryRepo;

    @Autowired
    public PartnerIndexServiceImpl(PartnerProjectionQueryRepository queryRepository,
                              PartnerEventRepository partnerEventRepository,
                              @Qualifier(value = "partnerEventHandler") EventHandler<Event<Entity>, Index> indexEventHandler,
                              MessageSource msgSource) {
        this.queryRepository = queryRepository;
        this.partnerEventRepository = partnerEventRepository;
        this.indexEventHandler = indexEventHandler;
        this.msgSource = msgSource;
    }

    @Override
    public void partnerReIndexing() {
        logger.info("ReIndexing start time : "+new Date());

        List<PartnerEvent> partnerList = new ArrayList<>();
        Pageable pageable = CassandraPageRequest.of(0, 5);
        Slice<PartnerEvent> page = partnerEventRepository.findAll(pageable);
        partnerList.addAll(page.getContent());
        while (page.hasNext()){
            page = partnerEventRepository.findAll(page.nextPageable());
            partnerList.addAll(page.getContent());
        };

        if (partnerList != null) {
            partnerList.parallelStream().forEach(event -> {
                Index index = createPartnerProjection(event);
                indexEventHandler.reIndexEvent(event, index);
            });
        }
        logger.info("ReIndexing end time : "+new Date());
    }


    /*public Slice<PartnerEvent> getPartnersOnBatch(Pageable pageable){
        Slice<PartnerEvent> events = partnerEventRepository.findAll(pageable);
        return events;
    }*/


    private Index createPartnerProjection(PartnerEvent event) {
        PartnerProjectionView.PartnerProjectViewBuilder builder = PartnerProjectionView.builder();

        Partner partner = (Partner) event.getEntity();

        if (partner.getGlobalPartnerRef() != null) {
            String uuid = partner.getGlobalPartnerRef().getUuid();
            if (uuid != null && globalPartnerQueryRepo.findByIdentifier(uuid) == null) {
                throw new BadRequestException("105", "Global Partner with uuid: " + uuid + " doesn't exist");
            }
        }

        builder.uuid(partner.getId());

        List<Attributes> paList = partner.getPartnerAttributes().stream()
                .filter(pa -> pa.getAttributeGroup().equalsIgnoreCase(GROUP_NAME_PARTNER)).map(pa -> pa.getAttributes())
                .findFirst().orElse(null);

        if (paList != null && !paList.isEmpty()) {
            paList.stream().forEach(a -> {
                if ("partnerTaxRegime".equalsIgnoreCase(a.getName())) {
                    builder.partnerTaxRegion(a.getValues().stream()
                            .filter(w -> "*".equals(w.getLang()) || "en".equalsIgnoreCase(w.getLang()))
                            .map(w -> w.getValue()).findFirst().orElse(null));
                } else if ("taxOrganisationType".equalsIgnoreCase(a.getName())) {
                    builder.taxOrganisationType(a.getValues().stream()
                            .filter(w -> "*".equals(w.getLang()) || "en".equalsIgnoreCase(w.getLang()))
                            .map(w -> w.getValue()).findFirst().orElse(null));
                } else if ("partnerStatus".equalsIgnoreCase(a.getName())) {
                    builder.status(a.getValues().stream()
                            .filter(w -> "*".equals(w.getLang()) || "en".equalsIgnoreCase(w.getLang()))
                            .map(w -> w.getValue()).findFirst().orElse(null));
                } else if ("partnername".equalsIgnoreCase(a.getName())) {
                    builder.name(a.getValues().stream()
                            .filter(w -> "*".equals(w.getLang()) || "en".equalsIgnoreCase(w.getLang()))
                            .map(w -> w.getValue()).findFirst().orElse(null));
                } else if ("partnernumber".equalsIgnoreCase(a.getName())) {
                    builder.number(a.getValues().stream()
                            .filter(w -> "*".equals(w.getLang()) || "en".equalsIgnoreCase(w.getLang()))
                            .map(w -> w.getValue()).findFirst().orElse(null));
                }
            });
        }

        return builder.build();
    }

}

莫基托

@RunWith(SpringRunner.class)
public class PartnerIndexServiceImplTest {

    @MockBean
    private PartnerProjectionQueryRepository queryRepository;
    @MockBean
    private PartnerEventRepository partnerEventRepository;
    @MockBean
    private EventHandler<Event<Entity>, Index> partnerEventHandler;
    @MockBean
    private MessageSource msgSource;

    PartnerIndexService partnerService;

    @Before
    public void setup() {
        partnerService = new PartnerIndexServiceImpl(queryRepository, partnerEventRepository, partnerEventHandler,
                msgSource);
    }

    @Test
    public void partnerReIndexing_withPartnerEvent()throws Exception{


        Pageable page = CassandraPageRequest.of(0,5);



        when(partnerEventRepository.findAll(page)).thenReturn(new SliceImpl<>(Collections.EMPTY_LIST));
        verify(partnerEventRepository,times(1)).findAll(page);

    }

}



共有1个答案

靳金鹏
2023-03-14

你把@Test称为“partnerReIndexing”,但我看不到对partnerService的调用。partnerReIndexing()。这有用吗?

@Test
public void partnerReIndexing_withPartnerEvent()throws Exception{
    Pageable page = CassandraPageRequest.of(0,5);
    when(partnerEventRepository.findAll(page)).thenReturn(new SliceImpl<>(Collections.EMPTY_LIST));
    // HERE COMES THE NEW LINE, THAT "ACT" PART OF THE TEST:
    partnerService.partnerReIndexing();
    verify(partnerEventRepository,times(1)).findAll(page);
}
 类似资料:
  • 我知道怎么解决这个问题吗?

  • Mocking resttemplate.exchange()不起作用。restTemplate.exchange()mocking的响应在BDS适配器类中给出null值。我的测试用例由于BDSAdapter类中的空指针异常而失败。(response.getStatusCodeValue()提供空指针异常。.mockito提示) 未使用...->at com..policydetails_adap

  • 如何模拟服务类中使用的助手方法。我试着找,但找不到,你能指导我吗?如何模拟服务类中使用的助手方法。我试着找,但找不到,你能指导我吗? 服务类功能: public void checkExistance(字符串名称){ } 这是测试逻辑:@SpringBootTest@RunWith(MockitoJUnitRunner.class)公共类ApiUsageServiceTests{MongoOper

  • 我有自定义的Log4j2 appender: 我想模拟:

  • 我在摆弄弹力靴,但每向前走一步,就会让我后退两步。 我将我的简单应用程序与Springboot连接在一起,但我没有得到这个错误: 还有这一点: 我不用任何数据库。应用程序非常简单。下面是主要的类: 下面是其他两个类和: 就是这样。尽管它可能很简单。 下面是文件结构以及build.gradle文件内容: 能有人请帮助我让这个小程序运行,指出我在正确的方向,以解决这个问题? 事先好心谢谢你。

  • 请求执行错误。Endpoint=DefaultEndPoint{serviceURL='http://localhost:8761/eureka/}是在docker windows中运行时提供的,但在STS中运行spring boot app时,它是在eureka服务器上注册的。 对于我在docker中运行的服务器docker run-p 8761:8080 serverimagename对于我在