Best Mockito code snippet using org.mockito.junit.MockitoJUnitRunner.MockitoJUnit.rule
Source:StrictRunnerTest.java
1/*2 * Copyright (c) 2017 Mockito contributors3 * This program is made available under the terms of the MIT License.4 */5package org.mockitousage.junitrunner;6import org.junit.Before;7import org.junit.Rule;8import org.junit.Test;9import org.junit.runner.JUnitCore;10import org.junit.runner.Result;11import org.junit.runner.RunWith;12import org.mockito.Mock;13import org.mockito.exceptions.misusing.UnnecessaryStubbingException;14import org.mockito.junit.MockitoJUnit;15import org.mockito.junit.MockitoRule;16import org.mockito.junit.MockitoJUnitRunner;17import org.mockitousage.IMethods;18import org.mockitoutil.JUnitResultAssert;19import org.mockitoutil.TestBase;20import static org.junit.Assert.assertEquals;21import static org.mockito.Mockito.mock;22import static org.mockito.Mockito.when;23public class StrictRunnerTest extends TestBase {24 JUnitCore runner = new JUnitCore();25 @Test public void succeeds_when_all_stubs_were_used() {26 //when27 Result result = runner.run(28 StubbingInConstructorUsed.class,29 StubbingInBeforeUsed.class,30 StubbingInTestUsed.class31 );32 //then33 JUnitResultAssert.assertThat(result).isSuccessful();34 }35 @Test public void fails_when_stubs_were_not_used() {36 Class[] tests = {StubbingInConstructorUnused.class,37 StubbingInBeforeUnused.class,38 StubbingInTestUnused.class};39 //when40 Result result = runner.run(tests);41 //then42 JUnitResultAssert.assertThat(result).fails(3, UnnecessaryStubbingException.class);43 }44 @Test public void does_not_report_unused_stubs_when_different_failure_is_present() {45 //when46 Result result = runner.run(WithUnrelatedAssertionFailure.class);47 //then48 JUnitResultAssert.assertThat(result).fails(1, MyAssertionError.class);49 }50 @Test public void runner_can_coexist_with_rule() {51 //I don't believe that this scenario is useful52 //I only wish that Mockito does not break awkwardly when both: runner & rule is used53 //when54 Result result = runner.run(RunnerAndRule.class);55 //then56 JUnitResultAssert.assertThat(result).fails(1, UnnecessaryStubbingException.class);57 }58 @Test public void runner_in_multi_threaded_tests() {59 //when60 Result result = runner.run(StubUsedFromDifferentThread.class);61 //then62 JUnitResultAssert.assertThat(result).isSuccessful();63 }64 @RunWith(MockitoJUnitRunner.class)65 public static class StubbingInConstructorUsed extends StubbingInConstructorUnused {66 @Test public void test() {67 assertEquals("1", mock.simpleMethod(1));68 }69 }70 @RunWith(MockitoJUnitRunner.Strict.class) //using Strict to make sure it does the right thing71 public static class StubbingInConstructorUnused {72 IMethods mock = when(mock(IMethods.class).simpleMethod(1)).thenReturn("1").getMock();73 @Test public void dummy() {}74 }75 @RunWith(MockitoJUnitRunner.class)76 public static class StubbingInBeforeUsed extends StubbingInBeforeUnused {77 @Test public void test() {78 assertEquals("1", mock.simpleMethod(1));79 }80 }81 @RunWith(MockitoJUnitRunner.class)82 public static class StubbingInBeforeUnused {83 @Mock IMethods mock;84 @Before public void before() {85 when(mock.simpleMethod(1)).thenReturn("1");86 }87 @Test public void dummy() {}88 }89 @RunWith(MockitoJUnitRunner.class)90 public static class StubbingInTestUsed {91 @Test public void test() {92 IMethods mock = mock(IMethods.class);93 when(mock.simpleMethod(1)).thenReturn("1");94 assertEquals("1", mock.simpleMethod(1));95 }96 }97 @RunWith(MockitoJUnitRunner.class)98 public static class StubbingInTestUnused {99 @Test public void test() {100 IMethods mock = mock(IMethods.class);101 when(mock.simpleMethod(1)).thenReturn("1");102 mock.simpleMethod(2); //different arg103 }104 }105 private static class MyAssertionError extends AssertionError {}106 @RunWith(MockitoJUnitRunner.class)107 public static class WithUnrelatedAssertionFailure {108 IMethods mock = mock(IMethods.class);109 IMethods mock2 = mock(IMethods.class);110 @Before public void before() {111 when(mock2.simpleMethod("unused stubbing")).thenReturn("");112 }113 @Test public void passing_test() {114 when(mock.simpleMethod(1)).thenReturn("1");115 assertEquals("1", mock.simpleMethod(1));116 }117 @Test public void failing_test() {118 throw new MyAssertionError();119 }120 }121 @RunWith(MockitoJUnitRunner.class)122 public static class RunnerAndRule {123 public @Rule MockitoRule rule = MockitoJUnit.rule();124 IMethods mock = mock(IMethods.class);125 @Test public void passing_test() {126 when(mock.simpleMethod(1)).thenReturn("1");127 mock.simpleMethod(2);128 }129 }130 @RunWith(MockitoJUnitRunner.class)131 public static class StubUsedFromDifferentThread {132 IMethods mock = mock(IMethods.class);133 @Test public void passing_test() throws Exception {134 //stubbing is done in main thread:135 when(mock.simpleMethod(1)).thenReturn("1");136 //stubbing is used in a different thread137 //stubbing should not be reported as unused by the runner138 Thread t = new Thread() {139 public void run() {140 mock.simpleMethod(1);141 }142 };143 t.start();144 t.join();145 }146 }147}...
Source:AnnotationTest.java
1package dmitr2ish.com.github.annotations.support;2import org.junit.Before;3import org.junit.Rule;4import org.junit.Test;5import org.junit.runner.RunWith;6import org.mockito.InjectMocks;7import org.mockito.Mock;8import org.mockito.MockitoAnnotations;9import org.mockito.junit.MockitoJUnit;10import org.mockito.junit.MockitoJUnitRunner;11import org.mockito.junit.MockitoRule;12import java.time.LocalDate;13import java.util.ArrayList;14import java.util.List;15import static org.junit.Assert.assertEquals;16import static org.mockito.Mockito.when;17//we have three case of mock init:18// 1 - via @RunWith(MockitoJUnitRunner.class)19// 2 - via MockitoAnnotations.initMocks(this)20// 3 - via @Rule MockitoJUnit.rule();21//if we use initMocks we can delete this annotation22// @RunWith(MockitoJUnitRunner.class)//extension for mock's annotation use23public class AnnotationTest {24 @Rule//must be public25 public MockitoRule mockitoRule = MockitoJUnit.rule();//provide check our annotations26 @InjectMocks//here we point where we want to inject our mock's dependency27 private SBookService bookService;28 @Mock//dependency of test class29 private SBookRepository bookRepository;30// @Before31// public void beforeEach() {32// MockitoAnnotations.initMocks(this);33// }34 @Test35 public void demoCreateMocksUsingAnnotations() {36 SBook book1 = new SBook("1234", "Mockito in Action", 500, LocalDate.now());37 SBook book2 = new SBook("1235", "JUnit in Action", 400, LocalDate.now());38 List<SBook> newBooks = new ArrayList<>();39 newBooks.add(book1);40 newBooks.add(book2);41 when(bookRepository.findNewBooks(7)).thenReturn(newBooks);42 List<SBook> newBooksWithAppliedDiscount =43 bookService.getNewBooksWithAppliedDiscount(10, 7);44 assertEquals(2, newBooksWithAppliedDiscount.size());45 assertEquals(450, newBooksWithAppliedDiscount.get(0).getPrice());46 assertEquals(360, newBooksWithAppliedDiscount.get(1).getPrice());47 }48}...
Source:LoginActivityPresenterTest.java
1package com.foi_bois.zisprojekt;2import org.junit.Before;3import org.junit.Rule;4import org.junit.Test;5import org.junit.runner.RunWith;6import org.mockito.Mock;7import org.mockito.junit.MockitoJUnit;8import org.mockito.junit.MockitoJUnitRunner;9import org.mockito.junit.MockitoRule;10import com.foi_bois.zisprojekt.auth.LoginPresenter;11import com.foi_bois.zisprojekt.auth.LoginPresenterImpl;12import com.foi_bois.zisprojekt.auth.ui.LoginView;13import com.foi_bois.zisprojekt.model.User;14import static org.mockito.Mockito.*;15@RunWith(MockitoJUnitRunner.class)16public class LoginActivityPresenterTest {17 @Rule18 public MockitoRule mockitoRule = MockitoJUnit.rule(); //ako nam bude trebao neki drugi runner, a la Google SDK-a19 @Mock20 LoginView view;21 private LoginPresenter presenter;22 @Before23 public void setUp() {24 presenter = new LoginPresenterImpl(view, userRepository);25 }26 @Test public void shouldPassUserToView() {27 //given28 User currUser = new User("123", "234");29 when(userRepository.getCurrentUser()).thenReturn(currUser);30 //when31 presenter.validateUser();32 //then33 verify(view).greetUser(currUser);34 }35 @Test public void shouldHandleWrongPassword() {36 when(userRepository.getCurrentUser()).thenReturn(null);37 presenter.validateUser();38 verify(view).displayWrongPasswordError(null);39 }40 @Test public void shouldHandleError(){ //ako se pojavi iznimka, test provjerava zove li se u tom slucaju displayError()41 when(userRepository.getCurrentUser()).thenThrow(new RuntimeException("explosion"));42 presenter.validateUser();43 verify(view).displayError();44 }45}...
Source:MockitoRuleTest.java
1package com.learning.mockito;2import org.junit.Rule;3import org.junit.jupiter.api.Test;4import org.junit.runner.RunWith;5import org.mockito.Mock;6import org.mockito.junit.MockitoJUnit;7import org.mockito.junit.MockitoJUnitRunner;8import org.mockito.junit.MockitoRule;9import org.mockito.quality.Strictness;10import java.util.List;11/**12 * 23. Automatic instantiation of @Spies, @InjectMocks and constructor injection goodness (Since 1.9.0)13 * Mockito will now try to instantiate @Spy and will instantiate @InjectMocks fields using constructor injection, setter injection, or field injection.14 *15 * To take advantage of this feature you need to use MockitoAnnotations.openMocks(Object), MockitoJUnitRunner or MockitoRule.16 *17 * Read more about available tricks and the rules of injection in the javadoc for InjectMocks18 *19 *20 * //instead:21 * @Spy BeerDrinker drinker = new BeerDrinker();22 * //you can write:23 * @Spy BeerDrinker drinker;24 *25 * //same applies to @InjectMocks annotation:26 * @InjectMocks LocalPub;27 *28 * For More Information:29 * https://javadoc.io/static/org.mockito/mockito-core/3.5.11/org/mockito/junit/MockitoJUnit.html#rule--30 *31 */32//@RunWith(MockitoJUnitRunner.class)33public class MockitoRuleTest {34 //Creating new rule with recommended Strictness setting35 @Rule public MockitoRule rule = MockitoJUnit.rule().strictness(Strictness.STRICT_STUBS);36 @Mock37 private List list;38 @Test39 public void shouldDoSomething() {40 //list.add(100);41 //did not work.42 }43}...
Source:TemperatureConverterTest.java
1package ua.kopylov.temperature.converter;2import org.junit.Rule;3import org.junit.Test;4import org.junit.runner.RunWith;5import org.mockito.InjectMocks;6import org.mockito.Mock;7import org.mockito.junit.MockitoJUnit;8import org.mockito.junit.MockitoJUnitRunner;9import org.mockito.junit.MockitoRule;10import ua.kopylov.temperature.Temperature;11import ua.kopylov.temperature.extractor.Extractor;12import java.util.List;13import static org.junit.Assert.*;14import static org.mockito.Mockito.when;15@RunWith(MockitoJUnitRunner.class)16public class TemperatureConverterTest {17 @InjectMocks18 private TemperatureConverter converter;19 @Mock20 private Extractor extractor;21 @Rule public MockitoRule rule = MockitoJUnit.rule();22 @Test23 public void convertAbsoluteZero() {24 String temperature = "0K";25 when(extractor.get(temperature)).thenReturn(new Temperature(0d, TemperatureScale.KELVIN));26 List<Temperature> actual = converter.run(temperature);27 assertNotNull(actual);28 assertEquals(TemperatureScale.values().length - 1, actual.size());29 assertEquals(TemperatureScale.CELSIUS, actual.get(0).getScale());30 assertEquals(-273.15d, actual.get(0).getDegree(), 0.01d);31 assertEquals(TemperatureScale.FAHRENHEIT, actual.get(1).getScale());32 assertEquals(-459.67d, actual.get(1).getDegree(), 0.01d);33 }34 public void convertNull() {35 }36}...
Source:AbstractJUnitUnitTests.java
1package com.test;2import org.junit.Rule;3import org.mockito.junit.MockitoJUnit;4import org.mockito.junit.MockitoRule;5/**6 * Abstract unit test class for JUnit.7 *8 * <p>References:9 * <ul>10 * <li>Spring Framework:11 * <a href="http://docs.spring.io/spring/docs/current/spring-framework-reference/html/unit-testing.html">12 * 14. Unit Testing</a>13 * </li>14 * <li>Mockito:15 * <a href="http://site.mockito.org/mockito/docs/current/org/mockito/Mockito.html#9">16 * 9. Shorthand for mocks creation - @Mock annotation</a>17 * </li>18 * <li>19 * <a href="http://junit.org/junit4/cookbook.html">20 * JUnit Cookbook</a>21 * </li>22 * </ul>23 *24 * @see org.mockito.junit.MockitoJUnit#rule()25 * @see org.mockito.junit.MockitoRule26 * @see org.mockito.runners.MockitoJUnitRunner27 * @see org.mockito.MockitoAnnotations#initMocks(Object)28 * @author Bert Lee29 * @since 2014-8-1930 */31//@RunWith(MockitoJUnitRunner.class)32public abstract class AbstractJUnitUnitTests {33 @Rule // éæ JUnit34 public MockitoRule rule = MockitoJUnit.rule(); // @Mock 注解35// @Before // éæ JUnit36// public void initMocks() {37// MockitoAnnotations.initMocks(this); // @Mock 注解38// }39}...
Source:AdministratorRestControllerTest.java
1package com.slasher.slasherproductions.restapi;2import org.junit.Rule;3import org.junit.jupiter.api.Test;4import org.junit.runner.RunWith;5import org.mockito.junit.MockitoJUnit;6import org.mockito.junit.MockitoJUnitRunner;7import org.mockito.junit.MockitoRule;8import org.springframework.boot.test.context.SpringBootTest;9@RunWith(MockitoJUnitRunner.class)10@SpringBootTest11public class AdministratorRestControllerTest {12 @Rule13 public MockitoRule initRule = MockitoJUnit.rule();14 @Test15 void shouldReturnHttpStatusCreate() {16 }17}...
Source:BaseTest.java
1package com.gve.testapplication.test_common;2import org.junit.Rule;3import org.junit.runner.RunWith;4import org.mockito.junit.MockitoJUnit;5import org.mockito.junit.MockitoJUnitRunner;6import org.mockito.junit.MockitoRule;7@RunWith(MockitoJUnitRunner.StrictStubs.class)8public abstract class BaseTest {9 @Rule10 public final MockitoRule rule = MockitoJUnit.rule();11 @Rule12 public final RxSchedulerOverrideRule overrideSchedulersRule = new RxSchedulerOverrideRule();13}...
MockitoJUnit.rule
Using AI Code Generation
1import org.junit.Rule;2import org.junit.Test;3import org.mockito.junit.MockitoJUnit;4import org.mockito.junit.MockitoRule;5public class Test1 {6 public MockitoRule mockitoRule = MockitoJUnit.rule();7 public void test() {8 }9}10import org.junit.Rule;11import org.junit.Test;12import org.mockito.junit.MockitoJUnit;13import org.mockito.junit.MockitoRule;14public class Test2 {15 public MockitoRule mockitoRule = MockitoJUnit.rule();16 public void test() {17 }18}19import org.junit.Rule;20import org.junit.Test;21import org.mockito.junit.MockitoJUnit;22import org.mockito.junit.MockitoRule;23public class Test3 {24 public MockitoRule mockitoRule = MockitoJUnit.rule();25 public void test() {26 }27}28import org.junit.Rule;29import org.junit.Test;30import org.mockito.junit.MockitoJUnit;31import org.mockito.junit.MockitoRule;32public class Test4 {33 public MockitoRule mockitoRule = MockitoJUnit.rule();34 public void test() {35 }36}37import org.junit.Rule;38import org.junit.Test;39import org.mockito.junit.MockitoJUnit;40import org.mockito.junit.MockitoRule;41public class Test5 {42 public MockitoRule mockitoRule = MockitoJUnit.rule();43 public void test() {44 }45}46import org.junit.Rule;47import org.junit.Test;48import org.mockito.junit.MockitoJUnit;49import org.mockito.junit.MockitoRule;50public class Test6 {51 public MockitoRule mockitoRule = MockitoJUnit.rule();52 public void test() {53 }54}55import org.junit.Rule;56import
MockitoJUnit.rule
Using AI Code Generation
1package com.ack.junit.mockito;2import org.junit.Rule;3import org.junit.Test;4import org.junit.rules.ExpectedException;5import org.mockito.Mock;6import org.mockito.junit.MockitoJUnit;7import org.mockito.junit.MockitoRule;8import java.util.List;9import static org.junit.Assert.assertEquals;10import static org.junit.Assert.assertNull;11import static org.mockito.Mockito.when;12public class MockitoJUnitRuleTest {13 public MockitoRule mockitoRule = MockitoJUnit.rule();14 public ExpectedException expectedException = ExpectedException.none();15 private List<String> mockedList;16 public void testMockCreation() {17 assertNull( mockedList.get( 0 ) );18 assertNull( mockedList.toArray() );19 }20 public void testStubbing() {21 when( mockedList.get( 0 ) ).thenReturn( "first" );22 when( mockedList.get( 1 ) ).thenThrow( new RuntimeException() );23 assertEquals( "first", mockedList.get( 0 ) );24 expectedException.expect( RuntimeException.class );25 mockedList.get( 1 );26 }27}28-> at com.ack.junit.mockito.MockitoJUnitRuleTest.testStubbing(MockitoJUnitRuleTest.java:37)29 when(mock.isOk()).thenReturn(true);30 when(mock.isOk()).thenThrow(exception);31 doThrow(exception).when(mock).someVoidMethod();32 doAnswer(new Answer() {33 Object answer(InvocationOnAr
MockitoJUnit.rule
Using AI Code Generation
1package org.mockito.junit;2import org.junit.Rule;3import org.junit.Test;4import org.mockito.Mock;5import org.mockito.junit.MockitoJUnit;6import org.mockito.junit.MockitoRule;7import java.util.List;8public class MockitoJUnitRunnerTest {9 public MockitoRule rule = MockitoJUnit.rule();10 private List mockedList;11 public void test() {12 mockedList.add("one");13 }14}
MockitoJUnit.rule
Using AI Code Generation
1import org.junit.Rule;2import org.junit.Test;3import org.junit.runner.RunWith;4import org.mockito.Mock;5import org.mockito.junit.MockitoJUnit;6import org.mockito.junit.MockitoRule;7import java.util.List;8import static org.junit.Assert.assertEquals;9import static org.mockito.Mockito.when;10@RunWith(MockitoJUnitRunner.class)11public class Test1 {12 List mockList;13 public MockitoRule mockitoRule = MockitoJUnit.rule();14 public void test1() {15 when(mockList.get(0)).thenReturn("Hello World");16 assertEquals("Hello World", mockList.get(0));17 }18}
MockitoJUnit.rule
Using AI Code Generation
1import org.mockito.junit.MockitoJUnit;2import org.mockito.junit.MockitoRule;3import static org.mockito.Mockito.*;4import org.junit.runner.RunWith;5import org.mockito.junit.MockitoJUnitRunner;6import org.mockito.runners.MockitoJUnitRunner;7import org.junit.Rule;8import org.junit.Test;9import java.util.*;10@RunWith(MockitoJUnitRunner.class)11public class MyClassTest {12 public MockitoRule mockitoRule = MockitoJUnit.rule();13 public void test() {14 List mockedList = mock(List.class);15 mockedList.add("one");16 mockedList.clear();17 verify(mockedList).add("one");18 verify(mockedList).clear();19 }20}21 at org.mockito.internal.runners.util.RunnerProviderImpl.instantiate(RunnerProviderImpl.java:36)22 at org.mockito.internal.runners.util.RunnerProviderImpl.getRunner(RunnerProviderImpl.java:27)23 at org.mockito.internal.runners.DefaultInternalRunnerFactory.create(DefaultInternalRunnerFactory.java:11)24 at org.mockito.internal.runners.DefaultRunnerFactory.create(DefaultRunnerFactory.java:22)25 at org.mockito.internal.runners.StrictRunnerFactory.create(StrictRunnerFactory.java:14)26 at org.mockito.internal.runners.DefaultRunnerProvider$1.create(DefaultRunnerProvider.java:24)27 at org.mockito.internal.runners.DefaultRunnerProvider$1.create(DefaultRunnerProvider.java:21)28 at org.mockito.internal.runners.DefaultRunnerProvider.newInstance(DefaultRunnerProvider.java:32)29 at org.mockito.internal.runners.DefaultRunnerProvider.getRunner(DefaultRunnerProvider.java:37)30 at org.mockito.internal.runners.JUnit45AndHigherRunnerImpl.<init>(JUnit45AndHigherRunnerImpl.java:13)31 at org.mockito.runners.MockitoJUnitRunner.<init>(MockitoJUnitRunner.java:15)32 at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)33 at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)34 at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)35 at java.lang.reflect.Constructor.newInstance(Constructor.java:423)36 at org.mockito.internal.runners.util.RunnerProviderImpl.instantiate(RunnerProviderImpl.java:34)37 at org.mockito.internal.runners.util.RunnerProviderImpl.getRunner(RunnerProviderImpl.java:27)38 at org.mockito.internal.runners.DefaultInternalRunnerFactory.create(DefaultInternalRunnerFactory.java:11)
MockitoJUnit.rule
Using AI Code Generation
1import org.junit.Test;2import org.junit.runner.RunWith;3import org.mockito.Mock;4import org.mockito.junit.MockitoJUnit;5import org.mockito.junit.MockitoRule;6import static org.mockito.Mockito.*;7@RunWith(MockitoJUnitRunner.class)8public class MockitoJUnitRunner {9 List mockList;10 public void usingMockitoJUnitRunner() {11 mockList.add("one");12 verify(mockList).add("one");13 }14}15import org.junit.Test;16import org.junit.runner.RunWith;17import org.mockito.Mock;18import org.mockito.junit.MockitoJUnit;19import org.mockito.junit.MockitoRule;20import static org.mockito.Mockito.*;21@RunWith(MockitoJUnitRunner.class)22public class MockitoJUnitRunner {23 List mockList;24 public void usingMockitoJUnitRunner() {25 mockList.add("one");26 verify(mockList).add("one");27 }28}29import org.junit.Test;30import org.junit.runner.RunWith;31import org.mockito.Mock;32import org.mockito.junit.MockitoJUnit;33import org.mockito.junit.MockitoRule;34import static org.mockito.Mockito.*;35@RunWith(MockitoJUnitRunner.class)36public class MockitoJUnitRunner {37 List mockList;38 public void usingMockitoJUnitRunner() {39 mockList.add("one");40 verify(mockList).add("one");41 }42}43import org.junit.Test;44import org.junit.runner.RunWith;45import org.mockito.Mock;46import org.mockito.junit.MockitoJUnit;47import org.mockito.junit.MockitoRule;48import static org.mockito.Mockito.*;
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!