How to use initialValue method of org.mockito.junit.TestableJUnitRunner class

Best Mockito code snippet using org.mockito.junit.TestableJUnitRunner.initialValue

copy

Full Screen

...12import org.mockito.internal.util.Supplier;13import java.lang.reflect.InvocationTargetException;14public class TestableJUnitRunner extends MockitoJUnitRunner {15 private final static ThreadLocal<SimpleMockitoLogger> LOGGER = new ThreadLocal<SimpleMockitoLogger>() {16 protected SimpleMockitoLogger initialValue() {17 return new SimpleMockitoLogger();18 }19 };20 public TestableJUnitRunner(Class<?> klass) throws InvocationTargetException, InitializationError {21 super(new StrictRunner(new RunnerFactory().create(klass, new Supplier<MockitoTestListener>() {22 public MockitoTestListener get() {23 return new MismatchReportingTestListener(LOGGER.get());24 }25 }), klass));26 }27 public static SimpleMockitoLogger refreshedLogger() {28 return LOGGER.get().clear();29 }30}...

Full Screen

Full Screen

initialValue

Using AI Code Generation

copy

Full Screen

1import org.junit.Test;2import org.junit.runner.RunWith;3import org.mockito.runners.MockitoJUnitRunner;4import org.mockito.runners.TestableJUnitRunner;5@RunWith(MockitoJUnitRunner.class)6public class MockitoJUnitRunnerTest {7 public void testMockitoJUnitRunner() {8 TestableJUnitRunner runner = new TestableJUnitRunner(MockitoJUnitRunnerTest.class);9 runner.initialValue();10 }11}12org.mockito.runners.MockitoJUnitRunnerTest > testMockitoJUnitRunner() PASSED

Full Screen

Full Screen

initialValue

Using AI Code Generation

copy

Full Screen

1package com.example.mockito;2import org.junit.Test;3import org.junit.runner.RunWith;4import org.mockito.Mock;5import org.mockito.junit.TestableJUnitRunner;6import java.util.List;7import static org.junit.Assert.assertEquals;8import static org.junit.Assert.assertNotNull;9import static org.mockito.Mockito.when;10@RunWith(TestableJUnitRunner.class)11public class MockitoTest {12 List<String> mockedList;13 public void test() {14 when(mockedList.get(0)).thenReturn("first");15 assertNotNull(mockedList);16 assertEquals("first", mockedList.get(0));17 }18}19package com.example.mockito;20import org.junit.Test;21import org.junit.runner.RunWith;22import org.mockito.Mock;23import org.mockito.MockitoAnnotations;24import org.mockito.junit.TestableJUnitRunner;25import java.util.List;26import static org.junit.Assert.assertEquals;27import static org.junit.Assert.assertNotNull;28import static org.mockito.Mockito.when;29@RunWith(TestableJUnitRunner.class)30public class MockitoTest {31 List<String> mockedList;32 public MockitoTest() {33 MockitoAnnotations.initMocks(this);34 }35 public void test() {36 when(mockedList.get(0)).thenReturn("first");37 assertNotNull(mockedList);38 assertEquals("first", mockedList.get(0));39 }40}

Full Screen

Full Screen

initialValue

Using AI Code Generation

copy

Full Screen

1import static org.mockito.Mockito.*;2import static org.junit.Assert.*;3import org.junit.Test;4import org.junit.runner.RunWith;5import org.mockito.junit.TestableJUnitRunner;6@RunWith(TestableJUnitRunner.class)7public class MockitoJUnitRunnerTest {8 public static final String INITIAL_VALUE = "Initial Value";9 public void testMockObject() {10 String str = mock(String.class);11 assertEquals(INITIAL_VALUE, str);12 }13}14package com.javadevjournal.tutorials.corejava.mockito.runner;15import static org.mockito.Mockito.*;16import static org.junit.Assert.*;17import org.junit.Test;18import org.junit.runner.RunWith;19import org.mockito.MockSettings;20import org.mockito.junit.TestableJUnitRunner;21@RunWith(TestableJUnitRunner.class)22public class MockitoJUnitRunnerTest {23 public static final String INITIAL_VALUE = "Initial Value";24 public static final String DEFAULT_VALUE = "Default Value";25 public MockitoJUnitRunnerTest(String value) {26 assertEquals(INITIAL_VALUE, value);27 }28 public void testMockObject() {29 String str = mock(String.class);30 assertEquals(DEFAULT_VALUE, str);31 }32}33package com.javadevjournal.tutorials.corejava.mockito.runner;34import static org.mockito.Mockito.*;35import static org.junit.Assert.*;36import org.junit.Test;37import org.junit.runner.RunWith;38import org.mockito.MockSettings;39import org.mockito

Full Screen

Full Screen

initialValue

Using AI Code Generation

copy

Full Screen

1import org.junit.runner.RunWith;2import org.mockito.runners.TestableJUnitRunner;3@RunWith(TestableJUnitRunner.class)4public class TestableJUnitRunnerTest {5 public void test() {6 }7}8JVM name : Java HotSpot(TM) 64-Bit Server VM9 at org.mockito.internal.util.MockUtil.createMock(MockUtil.java:30)10 at org.mockito.internal.MockitoCore.mock(MockitoCore.java:59)11 at org.mockito.Mockito.mock(Mockito.java:1106)12 at org.mockito.Mockito.mock(Mockito.java:1080)13 at org.mockito.runners.TestableJUnitRunner$1.initialValue(TestableJUnitRunner.java:29)14 at org.mockito.runners.TestableJUnitRunner$1.initialValue(TestableJUnitRunner.java:26)15 at java.lang.ThreadLocal.setInitialValue(ThreadLocal.java:180)16 at java.lang.ThreadLocal.get(ThreadLocal.java:170)17 at org.mockito.runners.TestableJUnitRunner.createTest(TestableJUnitRunner.java:39)18 at org.junit.runners.BlockJUnit4ClassRunner.methodBlock(BlockJUnit4ClassRunner.java:276)19 at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)20 at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)21 at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)22 at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)23 at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)24 at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)25 at org.junit.runners.ParentRunner.run(ParentRunner.java:236)26 at org.junit.runner.JUnitCore.run(JUnitCore.java:157)27 at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTest

Full Screen

Full Screen

initialValue

Using AI Code Generation

copy

Full Screen

1@RunWith(TestableJUnitRunner.class)2public class MyTest {3 private Collaborator collaborator;4 public void test() {5 }6}7@RunWith(MockitoJUnitRunner.class)8public class MyTest {9 private Collaborator collaborator;10 public void test() {11 }12}13@RunWith(MockitoJUnitRunner.class)14public class MyTest {15 private Collaborator collaborator;16 public void test() {17 }18}19@RunWith(MockitoJUnitRunner.class)20public class MyTest {21 private Collaborator collaborator;22 public void test() {23 }24}25@RunWith(MockitoJUnitRunner.class)26public class MyTest {27 private Collaborator collaborator;28 public void test() {29 }30}

Full Screen

Full Screen

initialValue

Using AI Code Generation

copy

Full Screen

1@RunWith(TestableJUnitRunner.class)2public class MockitoTest {3 private List<String> mockedList;4 public void testMock() {5 mockedList.add("one");6 verify(mockedList).add("one");7 }8}9@RunWith(MockitoJUnitRunner.class)10public class MockitoTest {11 private List<String> mockedList;12 public void testMock() {13 mockedList.add("one");14 verify(mockedList).add("one");15 }16}17public class MockitoTest {18 public MockitoRule mockitoRule = MockitoJUnit.rule();19 private List<String> mockedList;20 public void testMock() {21 mockedList.add("one");22 verify(mockedList).add("one");23 }24}25public class MockitoTest {26 private List<String> mockedList;27 public void initMocks() {28 MockitoAnnotations.initMocks(this);29 }30 public void testMock() {31 mockedList.add("one");32 verify(mockedList).add("one");33 }34}35public class MockitoTest {36 private List<String> mockedList;37 public void initMocks() {38 MockitoAnnotations.openMocks(this);39 }40 public void testMock() {41 mockedList.add("one");42 verify(mockedList).add("one");43 }44}45public class MockitoTest {46 private List<String> mockedList;47 public void initMocks() {48 MockitoSession mockitoSession = Mockito.mockitoSession()49 .initMocks(this)50 .startMocking();51 }52 public void testMock() {53 mockedList.add("one");54 verify(mockedList).add("one");55 }56}

Full Screen

Full Screen

StackOverFlow community discussions

Questions
Discussion

Initialising mock objects - Mockito

org.mockito.exceptions.misusing.InvalidUseOfMatchersException for valid expression

JUnit and Mocks in Liferay

How to inject multiple mocks of the same interface

Mock a constructor with parameter

How to force implementation of a method in subclass without using abstract?

Can I delay a stubbed method response with Mockito?

Mocking static methods with Mockito

Android instrumentation tests with Mockito

What is the Mockito equivalent of expect().andReturn().times()

For the mocks initialization, using the runner or the MockitoAnnotations.initMocks are strictly equivalent solutions. From the javadoc of the MockitoJUnitRunner :

JUnit 4.5 runner initializes mocks annotated with Mock, so that explicit usage of MockitoAnnotations.initMocks(Object) is not necessary. Mocks are initialized before each test method.


The first solution (with the MockitoAnnotations.initMocks) could be used when you have already configured a specific runner (SpringJUnit4ClassRunner for example) on your test case.

The second solution (with the MockitoJUnitRunner) is the more classic and my favorite. The code is simpler. Using a runner provides the great advantage of automatic validation of framework usage (described by @David Wallace in this answer).

Both solutions allows to share the mocks (and spies) between the test methods. Coupled with the @InjectMocks, they allow to write unit tests very quickly. The boilerplate mocking code is reduced, the tests are easier to read. For example:

@RunWith(MockitoJUnitRunner.class)
public class ArticleManagerTest {

    @Mock private ArticleCalculator calculator;
    @Mock(name = "database") private ArticleDatabase dbMock;
    @Spy private UserProvider userProvider = new ConsumerUserProvider();

    @InjectMocks private ArticleManager manager;

    @Test public void shouldDoSomething() {
        manager.initiateArticle();
        verify(database).addListener(any(ArticleListener.class));
    }

    @Test public void shouldDoSomethingElse() {
        manager.finishArticle();
        verify(database).removeListener(any(ArticleListener.class));
    }
}

Pros: The code is minimal

Cons: Black magic. IMO it is mainly due to the @InjectMocks annotation. With this annotation "you loose the pain of code" (see the great comments of @Brice)


The third solution is to create your mock on each test method. It allow as explained by @mlk in its answer to have "self contained test".

public class ArticleManagerTest {

    @Test public void shouldDoSomething() {
        // given
        ArticleCalculator calculator = mock(ArticleCalculator.class);
        ArticleDatabase database = mock(ArticleDatabase.class);
        UserProvider userProvider = spy(new ConsumerUserProvider());
        ArticleManager manager = new ArticleManager(calculator, 
                                                    userProvider, 
                                                    database);

        // when 
        manager.initiateArticle();

        // then 
        verify(database).addListener(any(ArticleListener.class));
    }

    @Test public void shouldDoSomethingElse() {
        // given
        ArticleCalculator calculator = mock(ArticleCalculator.class);
        ArticleDatabase database = mock(ArticleDatabase.class);
        UserProvider userProvider = spy(new ConsumerUserProvider());
        ArticleManager manager = new ArticleManager(calculator, 
                                                    userProvider, 
                                                    database);

        // when 
        manager.finishArticle();

        // then
        verify(database).removeListener(any(ArticleListener.class));
    }
}

Pros: You clearly demonstrate how your api works (BDD...)

Cons: there is more boilerplate code. (The mocks creation)


My recommandation is a compromise. Use the @Mock annotation with the @RunWith(MockitoJUnitRunner.class), but do not use the @InjectMocks :

@RunWith(MockitoJUnitRunner.class)
public class ArticleManagerTest {

    @Mock private ArticleCalculator calculator;
    @Mock private ArticleDatabase database;
    @Spy private UserProvider userProvider = new ConsumerUserProvider();

    @Test public void shouldDoSomething() {
        // given
        ArticleManager manager = new ArticleManager(calculator, 
                                                    userProvider, 
                                                    database);

        // when 
        manager.initiateArticle();

        // then 
        verify(database).addListener(any(ArticleListener.class));
    }

    @Test public void shouldDoSomethingElse() {
        // given
        ArticleManager manager = new ArticleManager(calculator, 
                                                    userProvider, 
                                                    database);

        // when 
        manager.finishArticle();

        // then 
        verify(database).removeListener(any(ArticleListener.class));
    }
}

Pros: You clearly demonstrate how your api works (How my ArticleManager is instantiated). No boilerplate code.

Cons: The test is not self contained, less pain of code

https://stackoverflow.com/questions/15494926/initialising-mock-objects-mockito

Blogs

Check out the latest blogs from LambdaTest on this topic:

How To Handle Dynamic Dropdowns In Selenium WebDriver With Java

Joseph, who has been working as a Quality Engineer, was assigned to perform web automation for the company’s website.

What is Selenium Grid &#038; Advantages of Selenium Grid

Manual cross browser testing is neither efficient nor scalable as it will take ages to test on all permutations & combinations of browsers, operating systems, and their versions. Like every developer, I have also gone through that ‘I can do it all phase’. But if you are stuck validating your code changes over hundreds of browsers and OS combinations then your release window is going to look even shorter than it already is. This is why automated browser testing can be pivotal for modern-day release cycles as it speeds up the entire process of cross browser compatibility.

Migrating Test Automation Suite To Cypress 10

There are times when developers get stuck with a problem that has to do with version changes. Trying to run the code or test without upgrading the package can result in unexpected errors.

Are Agile Self-Managing Teams Realistic with Layered Management?

Agile software development stems from a philosophy that being agile means creating and responding to change swiftly. Agile means having the ability to adapt and respond to change without dissolving into chaos. Being Agile involves teamwork built on diverse capabilities, skills, and talents. Team members include both the business and software development sides working together to produce working software that meets or exceeds customer expectations continuously.

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Mockito automation tests on LambdaTest cloud grid

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

Most used method in TestableJUnitRunner

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful