2

在 mockito 中是否可以根据 mock 是否实际用于被测单元来验证在 mock 上调用了一个方法?

举个简单的例子,我为我的被测单元提供了一个模拟工厂(FooFactory),当调用 Foo.create() 时,它返回一个模拟(Foo)以供单元下的某些方法使用测试。我如何验证 Foo.method() 仅在被测单元调用 Foo.create() 时才被调用?

我设想代码看起来像这样:

@Before
public void init() {
  Foo mockFoo = mock(Foo.class);
  when(fooFactory.create()).thenReturn(mockFoo);
  test = new UnitUnderTest(fooFactory);
}

@Test
... may or may not create a foo ...

@After
public void cleanup() {
  if (verify(fooFactory).create()) {  // Here's the 'conditional verification'
    Foo mockFoo = fooFactory.create();
    verify(mockFoo).close();
  }
}

举一个更具体的例子,我的工厂返回一个我想确保关闭的 Reader 对象,但并非类中的每个方法都实际构造了一个 Reader。我显然可以将验证添加到我知道需要 Reader 的每个测试中,但这似乎需要大量重复工作。

4

2 回答 2

1

您确定要编写此测试吗?

我可以看到两种解决方案:

1)你真的想确保资源被创建和关闭,所以尝试编写一个测试,你可以在其中验证两个方法调用。

2)您要确保无论何时打开资源,它也会关闭。这可以作为生产代码中的断言来实现......

如果你真的想继续你的方法,你可以捕捉到第一次验证抛出的异常,如果 create() 方法没有被调用。在捕获中,您只需返回。

此外,您不应该在清理中进行验证,而应在实际测试方法中进行。

于 2010-12-09T23:57:08.087 回答
0

Honestly it sounds like your test is tooo complicated. It's been my experience of many projects and lots of unit testing that the best way to handle things is to ensure that each test tests one thing only. You can have as many asserts as you like, but it should be one method being called and one scenario tested. Anything mo and the test becomes too complex. Plus it makes it very hard for other developers to pick up the test at a later stage when developing the app further.

So I'd suggest breaking your test up into multiple tests, one per scenario and then see if you still need this.

于 2010-12-10T00:52:23.030 回答