Details
-
Type:
New Feature
-
Status:
Open
-
Priority:
Minor
-
Resolution: Unresolved
-
Affects Version/s: 2.5.1
-
Fix Version/s: None
-
Component/s: JMock 2.x.x Library
-
Labels:None
-
Number of attachments :
Description
When writing utility methods that set up the environment for tests by injecting mocks into static variables (for example), it is sometimes the case that a mock has already been injected into the variable in question in order to fulfil some other requirement of the current test. It would be useful if there were a method, probably in Mockery, that can check if a given object is a mock that was created by that Mockery, so that if such a mock has already been injected into the system under test it can be reused rather than replaced. Example:
public class SUT
{
public static SomeInterface staticVar;
public static void memberUnderTest () { ... }
}
...
@RunWith(JMock.class)
public class Tests
{
Mockery mockery = new JUnit4Mockery ();
@Test
public void testWithComplexSetup ()
private void setUpSomeCommonCondition ()
{ SUT.staticVar = mockery.mock(SomeInterface.class); mockery.checking (...); }private void setUpAnotherCommonCondition ()
{ // This is wrong... shouldn't inject a new mock here because the old one // needs to be used to satisfy the expectations set up in // setUpSomeCommonCondition. But we can't rely on that, because some tests // might call one method but not the other. SUT.staticVar = mockery.mock(SomeInterface.class); mockery.checking (...); }}
As you see, the test in this case would fail. Note that the two helper methods might be completely unrelated to each other, possibly even in two different utility classes that are used by numerous tests throughout a complex system, so coordinating which is to create the mock in advance would be difficult. Leaving the test itself to create the mock results in unnecessary code duplication between potentially large numbers of test methods that all use these helper methods.
A simple solution would be to allow something like:
if (!mockery.createdMock(SUT.staticVar))
SUT.staticVar = mockery.mock(SomeInterface.class);
The new method would return true for any object that was a mock it created, but false otherwise. Thus even if static state persisted between tests, as long as a new mockery is created for each test run, a new mock will be created for each test.