Skip to content

Commit ba511ec

Browse files
Add unit test example with mocking for plugin
1 parent 49e3cfc commit ba511ec

File tree

1 file changed

+45
-2
lines changed

1 file changed

+45
-2
lines changed

content/markdown/plugin-developers/plugin-testing.md

Lines changed: 45 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -35,9 +35,52 @@ The general wisdom is that your code should be mostly tested with unit tests, bu
3535

3636
## Using JUnit alone
3737

38-
In principle, you can write a unit test of a plugin Mojo the same way you'd write any other JUnit test case, by writing a class that `extends TestCase`.
38+
In principle, you can write a unit test of a plugin Mojo the same way you'd write any other JUnit test case.
39+
40+
When using injections in your Mojo, you can simply use a mocking framework such as Mockito to create mock instances of the injected dependencies,
41+
and pass them to the Mojo constructor (if using constructor injection) or set them on the Mojo instance (if using field injection).
42+
43+
Simple example using Mockito with constructor injection:
44+
45+
```java
46+
@Mojo(name = "sayhi")
47+
public class GreetingMojo extends AbstractMojo {
48+
49+
private final MavenProject project;
50+
51+
@Inject
52+
public GreetingMojo(MavenProject project) {
53+
this.project = project;
54+
}
55+
56+
@Override
57+
public void execute() throws MojoExecutionException {
58+
getLog().info("Hello, world.");
59+
}
60+
}
61+
```
3962

40-
However, many mojo methods need more information to work properly. For example, you'll probably need to inject a reference to a `MavenProject`, so your mojo can query project variables.
63+
and the corresponding unit test:
64+
65+
```java
66+
@ExtendWith(MockitoExtension.class)
67+
class GreetingMojoTest {
68+
@Mock
69+
private MavenProject mavenProject;
70+
71+
@InjectMocks
72+
private GreetingMojo mojo;
73+
74+
@Test
75+
void testExecute() throws MojoExecutionException {
76+
// Execute the Mojo
77+
mojo.execute();
78+
79+
// Verify behavior or state as needed
80+
// (e.g., check interactions with mock, etc.)
81+
}
82+
}
83+
```
4184

4285
## Using PlexusTestCase
4386

0 commit comments

Comments
 (0)