How to use method of org.mockito.InjectMocks class

Best Mockito code snippet using org.mockito.InjectMocks.

Run Mockito automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

copy
1/*
2 * Copyright (c) 2007 Mockito contributors
3 * This program is made available under the terms of the MIT License.
4 */
5package org.mockito;
6
7import java.lang.annotation.Documented;
8import java.lang.annotation.Retention;
9import java.lang.annotation.RetentionPolicy;
10import java.lang.annotation.Target;
11
12import static java.lang.annotation.ElementType.FIELD;
13
14/**
15 * <ul>
16 * <li>Allows shorthand mock and spy injection.</li>
17 * <li>Minimizes repetitive mock and spy injection.</li>
18 * </ul>
19 * <p>
20 * Currently it only supports setter injection. If you prefer constructor injection - please contribute a patch.
21 * <p>
22 * Mockito tries to inject by type (using name in case types are the same). 
23 * Mockito does not throw anything when injection fails - you will have to satisfy the dependencies manually.  
24 * <p>
25 * Example:
26 * <pre>
27 *   public class ArticleManagerTest extends SampleBaseTestCase {
28 *
29 *       &#064;Mock private ArticleCalculator calculator;
30 *       &#064;Mock private ArticleDatabase database;
31 *       &#064;Spy private UserProvider userProvider = new ConsumerUserProvider();
32 *
33 *       &#064;InjectMocks private ArticleManager manager = new ArticleManager();
34 *
35 *       &#064;Test public void shouldDoSomething() {
36 *           manager.initiateArticle();
37 *           verify(database).addListener(any(ArticleListener.class));
38 *       }
39 *   }
40 *
41 *   public class SampleBaseTestCase {
42 *
43 *       &#064;Before public void initMocks() {
44 *           MockitoAnnotations.initMocks(this);
45 *       }
46 *   }
47 * </pre>
48 *
49 * <b>The field annotated with &#064;InjectMocks must be initialized.</b>
50 * <p>
51 * <b><code>MockitoAnnotations.injectMocks(this)</code></b> method has to called to initialize annotated objects.
52 * <p>
53 * In above example, <code>injectMocks()</code> is called in &#064;Before (JUnit4) method of test's base class.
54 * For JUnit3 <code>injectMocks()</code> can go to <code>setup()</code> method of a base class.
55 * You can also put injectMocks() in your JUnit runner (&#064;RunWith) or use built-in runners: {@link org.mockito.runners.MockitoJUnitRunner}
56 */
57@Documented
58@Target( { FIELD })
59@Retention(RetentionPolicy.RUNTIME)
60public @interface InjectMocks {}
61
Full Screen
copy
1package com.learning.mockito;
2
3import org.junit.jupiter.api.AfterEach;
4import org.junit.jupiter.api.BeforeEach;
5import org.junit.jupiter.api.Test;
6import org.mockito.InjectMocks;
7import org.mockito.Mock;
8import org.mockito.MockitoAnnotations;
9import org.mockito.Spy;
10
11import java.util.ArrayList;
12import java.util.List;
13
14import static org.hamcrest.Matchers.any;
15import static org.mockito.Mockito.verify;
16
17class InjectMockTest extends SampleBaseTestCase{
18
19    @Mock
20    private ArticleCalculator calculator;
21    @Mock(name = "database")
22    private ArticleDatabase dbMock; // note the mock name attribute
23
24    @Spy
25    private UserProvider userProvider = new ConsumerUserProvider();
26
27    @InjectMocks
28    private ArticleManager manager;
29
30    @Test
31    public void shouldDoSomething() {
32        manager.initiateArticle();
33
34        //verify(database()).addListener(any(ArticleCalculator.class));
35    }
36
37}
38
39
40class SampleBaseTestCase {
41
42    private AutoCloseable closeable;
43
44    @BeforeEach
45    public void openMocks() {
46        closeable = MockitoAnnotations.openMocks(this);
47    }
48
49    @AfterEach
50    public void releaseMocks() throws Exception {
51        closeable.close();
52    }
53}
54
55class ArticleManager {
56
57    private ArticleDatabase database;
58    private ArticleCalculator calculator;
59
60    ArticleManager() {  }
61
62    ArticleManager(ArticleCalculator calculator, ArticleDatabase database) {
63        this.database = database;
64        this.calculator = calculator;
65    }
66
67    ArticleManager(ArticleObserver observer, boolean flag) {
68        // observer is not declared in the test above.
69        // flag is not mockable anyway
70    }
71
72    // setter
73    void setDatabase(ArticleDatabase database) { }
74
75    // setter
76    void setCalculator(ArticleCalculator calculator) { }
77
78    public void initiateArticle() {
79        System.out.println(database.toString()+" and " + calculator.toString());
80        database.addListener(calculator);
81
82    }
83
84    public ArticleDatabase getDatabase() {
85        return database;
86    }
87}
88
89class ArticleDatabase{
90
91    private List<ArticleCalculator> lists = new ArrayList<>();
92    public void addListener(ArticleCalculator calculator) {
93        System.out.println("Adding Listener");
94        lists.add(calculator);
95    }
96}
97
98class ArticleCalculator{
99
100}
101
102class ArticleObserver{
103
104}
105
106class UserProvider{
107
108}
109
110class ConsumerUserProvider extends UserProvider{
111
112}
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Trigger code on LambdaTest Cloud Grid

Execute automation tests with on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)