【问题标题】:How to throw exception when try to mock gremlin query?尝试模拟 gremlin 查询时如何抛出异常?
【发布时间】:2020-09-18 16:15:42
【问题描述】:

我正在尝试为抛出异常但不知何故抛出 null 而不是异常的情况编写单元测试。

我试图模拟的服务调用。

 private List<Vertex> getVertexList(final String vertexId, GraphTraversalSource graphTraversalSource, final int indexToLoop) {
        return graphTraversalSource.V(vertexId).repeat(in().dedup().simplePath()).until(loops().is(indexToLoop)).toList();
    }

我写了以下来模拟抛出异常

 @Mock(answer = RETURNS_DEEP_STUBS)
    private GraphTraversalSource gts;


  Mockito.when(gts.V(anyString()).repeat(any()).until((Predicate<Traverser<Vertex>>) any()).toList()).thenThrow(Exception.class);

有什么方法可以模拟它以抛出异常?提前致谢。

【问题讨论】:

    标签: unit-testing junit mockito gremlin


    【解决方案1】:

    假设您的gtsMockitoAnnotations.initMocks(this) 在测试的@Before 中调用,这种风格对我有用:

    GraphTraversal v = mock(GraphTraversal.class);
    GraphTraversal repeat = mock(GraphTraversal.class);
    GraphTraversal until = mock(GraphTraversal.class);
    when(gts.V(anyString())).thenReturn(v);
    when(v.repeat(any())).thenReturn(repeat);
    when(repeat.until((Predicate<Traverser<Vertex>>) any())).thenReturn(until);
    when(until.toList()).thenThrow(RuntimeException.class);
    gts.V("test-id").repeat(out()).until(__.loops().is(1)).toList();
    

    根据您正在做的事情,您可能会考虑避免模拟并在遍历本身中抛出异常:

    GraphTraversalSource g = EmptyGraph.instance().traversal();
    g.inject("test-id").sideEffect(x -> {
        throw new RuntimeException();
    }).toList();
    

    显然,这与您的模拟所做的有点不同,并且确实需要遍历才能真正让数据通过它(因此我使用inject() 开始遍历而不是V(),因为g 是绑定的在这种情况下,EmptyGraph

    【讨论】:

      猜你喜欢
      • 2018-04-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-23
      相关资源
      最近更新 更多