You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardexpand all lines: README.md
+30-10
Original file line number
Diff line number
Diff line change
@@ -1,8 +1,17 @@
1
1
# Mockito Object Injection
2
2
3
-
Inject Strings (or other objects) into your `@InjectMocks` targets [objects under test] without booting a Spring, Weld, CDI, Arquillian, EJB, or other container. Super lightweight and easy to use. Skip straight to Examples and Usage if you know what you're looking for.
3
+
## Preamble
4
4
5
-
## Problem
5
+
* Mock testing leads to highly focused tests where every variable is controlled.
The problem is, how does one Mock a String, Boolean, or other final type if those types are being Injected?
9
+
10
+
## Summary
11
+
12
+
This Junit Extension allows you to inject Strings (or any other object) into your `@InjectMocks` targets [objects under test] without booting a Spring, Weld, CDI, Arquillian, EJB, or other container. It's super lightweight, over 100,000x faster than Arquillian, and easy to use.
13
+
14
+
## Example Problem
6
15
7
16
Take this Spring Controller (or if you're using the far superior and modern CDI framework, think `@AppplicationScoped` instead of `@Controller` and `@Inject` instead of `@Autowired`)
8
17
@@ -30,15 +39,16 @@ If you wanted to write a _true unit test*_ with no external dependencies, you'd
30
39
31
40
```
32
41
@ExtendWith({ MockitoExtension.class })
33
-
public class MyControllerTest {
42
+
class MyControllerTest {
34
43
@InjectMocks
35
44
private MyController myController;
36
45
@Mock
37
46
private Logger log;
38
47
@Mock
39
48
private Authenticator auther;
40
49
41
-
public void testDoSomething() throws Exception {
50
+
@Test
51
+
void testDoSomething() throws Exception {
42
52
myController.doSomething();
43
53
// results in NPE because myController.securityEnabled is null
44
54
}
@@ -47,7 +57,7 @@ public class MyControllerTest {
47
57
48
58
* Testing a "unit" of code is a unit test. In Java, typically a class is the smallest unit of code.
49
59
50
-
## Examples
60
+
## Example Solution
51
61
52
62
This JUnit5 extension allows you to arbitrarily set any field on your `@InjectMocks`[class under test] target. The injections happen _very late_; they happen when you call any non-private method on the class under test.
// wahoo no NPE! Test the "if else" half of branch
81
93
}
82
94
}
83
95
```
84
96
85
-
## PostConstruct invocation
97
+
## @PostConstruct invocation
86
98
87
99
CDI and SpringFramework allow the use of `@PostConstruct`. This is like a constructor, except the method annotated will be invoked _after_ dependency injection is complete. This extension can be commanded to invoke the method annotated with `@PostConstruct` like so:
0 commit comments