Adding support for Mockito to an Eclipse target definition

In my previous post I showed how to add JUnit support to Eclipse target definitions. This allows plug-in developers to write and run unit tests (both regular and in-container) using all of the tools available in the Eclipse IDE.

I had a request to show how to add Mockito to the mix, so here it is. Mockito is available in the Eclipse Orbit repository and support can be added with the following target definition location.

<!-- Add Mockito support -->
<location includeAllPlatforms="false" includeConfigurePhase="true" includeMode="slicer" includeSource="true" type="InstallableUnit">
	<repository location="https://download.eclipse.org/tools/orbit/downloads/drops/R20201130205003/repository"/>
	<unit id="org.mockito" version="0.0.0"/>
	<unit id="net.bytebuddy.byte-buddy" version="0.0.0"/>
	<unit id="net.bytebuddy.byte-buddy-agent" version="0.0.0"/>
	<unit id="org.objenesis" version="0.0.0"/>
</location>

Adding Mockito in this way will allow you to create mocks using the @Mock annotation in combination with the an initMocks invocation.

class HelloWorldService_Mockito_MockWithInit_Test {

	@Mock
	private HelloWorldService helloWorldService;

	@BeforeEach
	void setUp() {
		MockitoAnnotations.initMocks(this);
	}

	@Test
	void test() {
		when(helloWorldService.sayHello()).thenReturn("Hello!");
		assertEquals("Hello!", helloWorldService.sayHello());
	}
}

You can also create mocks directly using the Mockito.mock method.

class HelloWorldService_Mockito_DirectMock_Test {

	@Test
	void test() {
		HelloWorldService helloWorldService = mock(HelloWorldService.class);
		when(helloWorldService.sayHello()).thenReturn("Hello!");

		assertEquals("Hello!", helloWorldService.sayHello());
	}
}

When running with JUnit 5 Mockito supports the running of tests using an extension – @ExtendWith(MockitoExtension.class). Unfortunately this is not yet available to Eclipse plug-in developers, though this is an open issue for Mockito.

Adding EasyMock support

EasyMock is also available in the Orbit repository, though the version is 2.4. The target platform location would be.

<!-- Add EasyMock support -->
<location includeAllPlatforms="false" includeConfigurePhase="true" includeMode="slicer" includeSource="true" type="InstallableUnit">
	<repository location="https://download.eclipse.org/tools/orbit/downloads/drops/R20201130205003/repository"/>
	<unit id="org.easymock" version="0.0.0"/>
</location>		

The most recent version of EasyMock does include OSGi metadata, so it would be fairly easy to download the JAR and add it to your own internal p2 repository, but it is a bit of extra work.

Wrapping up

I’ve updated the projects in the GitHub repository with the new target definition locations and also some simple Mockito examples.

https://github.com/modular-mind/pde-junit-support