尝试模拟 gremlin 查询时如何抛出异常?

How to throw exception when try to mock gremlin query?

我正在尝试为抛出异常但不知何故抛出 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);

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

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

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