Java 没有结果的期望块是否与验证块相同?
我理解,通常情况下,用于模拟具有不同返回值的值。例如:Java 没有结果的期望块是否与验证块相同?,java,jmockit,Java,Jmockit,我理解,通常情况下,用于模拟具有不同返回值的值。例如: new Expectations() {{ bar.getGreeting(); result = "Hello, world!"; times = 2; }}; 我注意到,结果是可选的。此时,该块仅确认该方法被调用了两次,如果没有调用,则抛出MissingInvocation错误。例如: @Test public void testRunFoo(@Mocked final Bar bar) { Foo f
new Expectations() {{
bar.getGreeting();
result = "Hello, world!";
times = 2;
}};
我注意到,结果
是可选的。此时,该块仅确认该方法被调用了两次,如果没有调用,则抛出MissingInvocation
错误。例如:
@Test
public void testRunFoo(@Mocked final Bar bar) {
Foo foo = new Foo(bar);
new Expectations() {{
bar.runBar();
times = 2;
}};
foo.runFooWithBarTwice(); //Successful
//foo.runFooWithoutBar(); //Will throw a MissingInvocationException
}
我注意到,此代码似乎与使用相同:
没有结果的
预期
块是否与验证
块相同?你能根据自己的喜好使用其中一种吗?或者,这两者之间有什么细微的差别,我没有注意到吗?你是对的,它们的工作原理是相似的。如果您在预期
块中模拟交互,则它们将被验证,类似于将它们放置在验证
块中
如果您在的介绍页面中查看JMockit的设计理念,它建议使用以下模式编写测试
@Test
public void aTestMethod(<any number of mock parameters>)
{
// Record phase: expectations on mocks are recorded; empty if nothing to record.
// Replay phase: invocations on mocks are "replayed"; code under test is exercised.
// Verify phase: expectations on mocks are verified; empty if nothing to verify.
}
@测试
公共无效aTestMethod()
{
//记录阶段:记录对模拟的期望;如果没有要记录的内容,则为空。
//重放阶段:模拟上的调用被“重放”;测试中的代码被执行。
//验证阶段:对模拟的预期已验证;如果无需验证,则为空。
}
记录
阶段的目的不是验证您正在测试的代码,而是确保您正在测试的代码具有运行测试所需的依赖项和交互。因此,Expectations
块的目的是记录模拟对象在Replay
阶段需要执行特定操作才能与测试代码交互的任何交互。这通常意味着返回特定值或确保交互使用正确的模拟对象
有时,我会在单元测试中添加上面JMockit文档中的三条注释,以帮助编写测试文档
最后,验证
块是您通常要对模拟对象交互进行验证的地方。注意,您还可以在验证
块之前、之后或内部使用标准Junit断言
@Test
public void aTestMethod(<any number of mock parameters>)
{
// Record phase: expectations on mocks are recorded; empty if nothing to record.
// Replay phase: invocations on mocks are "replayed"; code under test is exercised.
// Verify phase: expectations on mocks are verified; empty if nothing to verify.
}