Is there any way to move code out the MockedStatic curly brackets and make everything its own line, without side effects? Just curious looking at the template here, If there is no answer, thats fine. We have multiple MockedStatic, and its causing 2-3 layer curly brackets.
https://stackoverflow.com/a/62860455/15435022
assertEquals("foo", Foo.method());
try (MockedStatic mocked = mockStatic(Foo.class)) {
mocked.when(Foo::method).thenReturn("bar");
assertEquals("bar", Foo.method());
mocked.verify(Foo::method);
}
assertEquals("foo", Foo.method());
"In your case, something like this:"
@Test
public void testStaticMockWithVerification() throws SQLException {
try (MockedStatic<DriverManager> dummy = Mockito.mockStatic(DriverManager.class)) {
DatabaseConnectionFactory factory = new MySQLDatabaseConnectionFactory();
dummy.when(() -> DriverManager.getConnection("arg1", "arg2", "arg3"))
.thenReturn(new Connection() {/*...*/});
factory.getConnection();
dummy.verify(() -> DriverManager.getConnection(eq("arg1"), eq("arg2"), eq("arg3")));
}
}
If you just want to avoid deep nesting, you can put multiple "resources" (in this case, mockStatic
calls) in a single try
-with-resources statement.
try (MockedStatic<Foo> mocked1 = mockStatic(Foo.class);
MockedStatic<Bar> mocked2 = mockStatic(Bar.class);
MockedStatic<Baz> mocked3 = mockStatic(Baz.class)) {
// do your tests here...
}
If you really want to remove all the curly braces, you can always just manually call close()
yourself, but this is more error-prone, as you might forget to that.
MockedStatic<Foo> mocked1 = mockStatic(Foo.class);
MockedStatic<Bar> mocked2 = mockStatic(Bar.class);
MockedStatic<Baz> mocked3 = mockStatic(Baz.class);
// do your tests here...
mocked3.close();
mocked2.close();
mocked1.close();