首页 > 解决方案 > Is calling close() on object returned by MockitoAnnotations.openMocks(Object) is mandatory?

问题描述

I would like is it mandatory to call close() on object returned by MockitoAnnotations.openMocks(Object)? If answer is yes, why do I need to call it? Assume we have such an example:

public class MockitoAnnotationsOpenMocksTest {
@Mock
private Foo var;
@BeforeMethod
public void before() {
    MockitoAnnotations.openMocks(this);
}

@Test
public void foo() {
    Mockito.when(var.name()).thenReturn("foo");
    System.out.println("test foo" + ", var name " + var.name());
}
@Test
public void foo2() {
    System.out.println("test foo2" + ", var name " + var.name());

}
private class Foo {
    String name() {
        return "";
    }
}

}

running it with testng result is:

[RemoteTestNG] detected TestNG version 6.14.2
test foo, var name foo
test foo2, var name null
PASSED: foo
PASSED: foo2
PASSED: foo2

AFAIK in every call of @BeforeMethod MockitoAnnotations.openMocks(this); initializes var object one more time, so I do not see any sense to use close() method after every test method.

标签: javamockito

解决方案


The documentation says:

If static method mocks are used, it is required to close the initialization. Additionally, if using third-party mock-makers, other life-cycles might be handled by the open-release routine.

So no, tests won't fail under all circumstances if you don't close the mocks, but there are cases where it's necessary, so any generic test framework should make sure to close().


推荐阅读