Best Mockito code snippet using org.mockitousage.constructor.CreatingMocksWithConstructorTest
Source:CreatingMocksWithConstructorTest.java  
...10import org.mockito.exceptions.base.MockitoException;11import org.mockito.mock.SerializableMode;12import org.mockitousage.IMethods;13import org.mockitoutil.TestBase;14public class CreatingMocksWithConstructorTest extends TestBase {15    abstract static class AbstractMessage {16        private final String message;17        AbstractMessage() {18            this.message = "hey!";19        }20        AbstractMessage(String message) {21            this.message = message;22        }23        AbstractMessage(int i) {24            this.message = String.valueOf(i);25        }26        String getMessage() {27            return message;28        }29    }30    static class Message extends CreatingMocksWithConstructorTest.AbstractMessage {}31    class InnerClass extends CreatingMocksWithConstructorTest.AbstractMessage {}32    @Test33    public void can_create_mock_with_constructor() {34        CreatingMocksWithConstructorTest.Message mock = Mockito.mock(CreatingMocksWithConstructorTest.Message.class, Mockito.withSettings().useConstructor().defaultAnswer(Mockito.CALLS_REAL_METHODS));35        // the message is a part of state of the mocked type that gets initialized in constructor36        Assert.assertEquals("hey!", mock.getMessage());37    }38    @Test39    public void can_mock_abstract_classes() {40        CreatingMocksWithConstructorTest.AbstractMessage mock = Mockito.mock(CreatingMocksWithConstructorTest.AbstractMessage.class, Mockito.withSettings().useConstructor().defaultAnswer(Mockito.CALLS_REAL_METHODS));41        Assert.assertEquals("hey!", mock.getMessage());42    }43    @Test44    public void can_spy_abstract_classes() {45        CreatingMocksWithConstructorTest.AbstractMessage mock = Mockito.spy(CreatingMocksWithConstructorTest.AbstractMessage.class);46        Assert.assertEquals("hey!", mock.getMessage());47    }48    @Test49    public void can_spy_abstract_classes_with_constructor_args() {50        CreatingMocksWithConstructorTest.AbstractMessage mock = Mockito.mock(CreatingMocksWithConstructorTest.AbstractMessage.class, Mockito.withSettings().useConstructor("hello!").defaultAnswer(Mockito.CALLS_REAL_METHODS));51        Assert.assertEquals("hello!", mock.getMessage());52    }53    @Test54    public void can_spy_abstract_classes_with_constructor_primitive_args() {55        CreatingMocksWithConstructorTest.AbstractMessage mock = Mockito.mock(CreatingMocksWithConstructorTest.AbstractMessage.class, Mockito.withSettings().useConstructor(7).defaultAnswer(Mockito.CALLS_REAL_METHODS));56        Assert.assertEquals("7", mock.getMessage());57    }58    @Test59    public void can_spy_abstract_classes_with_constructor_array_of_nulls() {60        CreatingMocksWithConstructorTest.AbstractMessage mock = Mockito.mock(CreatingMocksWithConstructorTest.AbstractMessage.class, Mockito.withSettings().useConstructor(new Object[]{ null }).defaultAnswer(Mockito.CALLS_REAL_METHODS));61        Assert.assertNull(mock.getMessage());62    }63    @Test64    public void can_spy_abstract_classes_with_casted_null() {65        CreatingMocksWithConstructorTest.AbstractMessage mock = Mockito.mock(CreatingMocksWithConstructorTest.AbstractMessage.class, Mockito.withSettings().useConstructor(((String) (null))).defaultAnswer(Mockito.CALLS_REAL_METHODS));66        Assert.assertNull(mock.getMessage());67    }68    @Test69    public void can_spy_abstract_classes_with_null_varargs() {70        try {71            Mockito.mock(CreatingMocksWithConstructorTest.AbstractMessage.class, Mockito.withSettings().useConstructor(null).defaultAnswer(Mockito.CALLS_REAL_METHODS));72            Assert.fail();73        } catch (IllegalArgumentException e) {74            assertThat(e).hasMessageContaining(("constructorArgs should not be null. " + "If you need to pass null, please cast it to the right type, e.g.: useConstructor((String) null)"));75        }76    }77    @Test78    public void can_mock_inner_classes() {79        CreatingMocksWithConstructorTest.InnerClass mock = Mockito.mock(CreatingMocksWithConstructorTest.InnerClass.class, Mockito.withSettings().useConstructor().outerInstance(this).defaultAnswer(Mockito.CALLS_REAL_METHODS));80        Assert.assertEquals("hey!", mock.getMessage());81    }82    public static class ThrowingConstructorClass {83        public ThrowingConstructorClass() {84            throw new RuntimeException();85        }86    }87    @Test88    public void explains_constructor_exceptions() {89        try {90            Mockito.mock(CreatingMocksWithConstructorTest.ThrowingConstructorClass.class, Mockito.withSettings().useConstructor().defaultAnswer(Mockito.CALLS_REAL_METHODS));91            Assert.fail();92        } catch (MockitoException e) {93            assertThat(e).hasRootCauseInstanceOf(RuntimeException.class);94            assertThat(e.getCause()).hasMessageContaining("Please ensure the target class has a 0-arg constructor and executes cleanly.");95        }96    }97    static class HasConstructor {98        HasConstructor(String x) {99        }100    }101    @Test102    public void exception_message_when_constructor_not_found() {103        try {104            // when105            Mockito.spy(CreatingMocksWithConstructorTest.HasConstructor.class);106            // then107            Assert.fail();108        } catch (MockitoException e) {109            assertThat(e).hasMessage("Unable to create mock instance of type 'HasConstructor'");110            assertThat(e.getCause()).hasMessageContaining("Please ensure that the target class has a 0-arg constructor.");111        }112    }113    static class Base {}114    static class ExtendsBase extends CreatingMocksWithConstructorTest.Base {}115    static class ExtendsExtendsBase extends CreatingMocksWithConstructorTest.ExtendsBase {}116    static class UsesBase {117        public UsesBase(CreatingMocksWithConstructorTest.Base b) {118            constructorUsed = "Base";119        }120        public UsesBase(CreatingMocksWithConstructorTest.ExtendsBase b) {121            constructorUsed = "ExtendsBase";122        }123        private String constructorUsed = null;124        String getConstructorUsed() {125            return constructorUsed;126        }127    }128    @Test129    public void can_mock_unambigous_constructor_with_inheritance_base_class_exact_match() {130        CreatingMocksWithConstructorTest.UsesBase u = Mockito.mock(CreatingMocksWithConstructorTest.UsesBase.class, Mockito.withSettings().useConstructor(new CreatingMocksWithConstructorTest.Base()).defaultAnswer(Mockito.CALLS_REAL_METHODS));131        Assert.assertEquals("Base", u.getConstructorUsed());132    }133    @Test134    public void can_mock_unambigous_constructor_with_inheritance_extending_class_exact_match() {135        CreatingMocksWithConstructorTest.UsesBase u = Mockito.mock(CreatingMocksWithConstructorTest.UsesBase.class, Mockito.withSettings().useConstructor(new CreatingMocksWithConstructorTest.ExtendsBase()).defaultAnswer(Mockito.CALLS_REAL_METHODS));136        Assert.assertEquals("ExtendsBase", u.getConstructorUsed());137    }138    @Test139    public void can_mock_unambigous_constructor_with_inheritance_non_exact_match() {140        CreatingMocksWithConstructorTest.UsesBase u = Mockito.mock(CreatingMocksWithConstructorTest.UsesBase.class, Mockito.withSettings().useConstructor(new CreatingMocksWithConstructorTest.ExtendsExtendsBase()).defaultAnswer(Mockito.CALLS_REAL_METHODS));141        Assert.assertEquals("ExtendsBase", u.getConstructorUsed());142    }143    static class UsesTwoBases {144        public UsesTwoBases(CreatingMocksWithConstructorTest.Base b1, CreatingMocksWithConstructorTest.Base b2) {145            constructorUsed = "Base,Base";146        }147        public UsesTwoBases(CreatingMocksWithConstructorTest.ExtendsBase b1, CreatingMocksWithConstructorTest.Base b2) {148            constructorUsed = "ExtendsBase,Base";149        }150        public UsesTwoBases(CreatingMocksWithConstructorTest.Base b1, CreatingMocksWithConstructorTest.ExtendsBase b2) {151            constructorUsed = "Base,ExtendsBase";152        }153        private String constructorUsed = null;154        String getConstructorUsed() {155            return constructorUsed;156        }157    }158    @Test159    public void can_mock_unambigous_constructor_with_inheritance_multiple_base_class_exact_match() {160        CreatingMocksWithConstructorTest.UsesTwoBases u = Mockito.mock(CreatingMocksWithConstructorTest.UsesTwoBases.class, Mockito.withSettings().useConstructor(new CreatingMocksWithConstructorTest.Base(), new CreatingMocksWithConstructorTest.Base()).defaultAnswer(Mockito.CALLS_REAL_METHODS));161        Assert.assertEquals("Base,Base", u.getConstructorUsed());162    }163    @Test164    public void can_mock_unambigous_constructor_with_inheritance_first_extending_class_exact_match() {165        CreatingMocksWithConstructorTest.UsesTwoBases u = Mockito.mock(CreatingMocksWithConstructorTest.UsesTwoBases.class, Mockito.withSettings().useConstructor(new CreatingMocksWithConstructorTest.ExtendsBase(), new CreatingMocksWithConstructorTest.Base()).defaultAnswer(Mockito.CALLS_REAL_METHODS));166        Assert.assertEquals("ExtendsBase,Base", u.getConstructorUsed());167    }168    @Test169    public void can_mock_unambigous_constructor_with_inheritance_second_extending_class_exact_match() {170        CreatingMocksWithConstructorTest.UsesTwoBases u = Mockito.mock(CreatingMocksWithConstructorTest.UsesTwoBases.class, Mockito.withSettings().useConstructor(new CreatingMocksWithConstructorTest.Base(), new CreatingMocksWithConstructorTest.ExtendsBase()).defaultAnswer(Mockito.CALLS_REAL_METHODS));171        Assert.assertEquals("Base,ExtendsBase", u.getConstructorUsed());172    }173    @Test174    public void fail_when_multiple_matching_constructors_with_inheritence() {175        try {176            // when177            Mockito.mock(CreatingMocksWithConstructorTest.UsesTwoBases.class, Mockito.withSettings().useConstructor(new CreatingMocksWithConstructorTest.ExtendsBase(), new CreatingMocksWithConstructorTest.ExtendsBase()));178            // then179            Assert.fail();180        } catch (MockitoException e) {181            // TODO the exception message includes Mockito internals like the name of the generated class name.182            // I suspect that we could make this exception message nicer.183            assertThat(e).hasMessage("Unable to create mock instance of type 'UsesTwoBases'");184            assertThat(e.getCause()).hasMessageContaining(("Multiple constructors could be matched to arguments of types " + ("[org.mockitousage.constructor.CreatingMocksWithConstructorTest$ExtendsBase, " + "org.mockitousage.constructor.CreatingMocksWithConstructorTest$ExtendsBase]"))).hasMessageContaining(("If you believe that Mockito could do a better job deciding on which constructor to use, please let us know.\n" + ("Ticket 685 contains the discussion and a workaround for ambiguous constructors using inner class.\n" + "See https://github.com/mockito/mockito/issues/685")));185        }186    }187    @Test188    public void mocking_inner_classes_with_wrong_outer_instance() {189        try {190            // when191            Mockito.mock(CreatingMocksWithConstructorTest.InnerClass.class, Mockito.withSettings().useConstructor().outerInstance(123).defaultAnswer(Mockito.CALLS_REAL_METHODS));192            // then193            Assert.fail();194        } catch (MockitoException e) {195            assertThat(e).hasMessage("Unable to create mock instance of type 'InnerClass'");196            // TODO it would be nice if all useful information was in the top level exception, instead of in the exception's cause197            // also applies to other scenarios in this test198            assertThat(e.getCause()).hasMessageContaining(("Please ensure that the target class has a 0-arg constructor" + " and provided outer instance is correct."));199        }200    }201    @SuppressWarnings({ "CheckReturnValue", "MockitoUsage" })202    @Test203    public void mocking_interfaces_with_constructor() {204        // at the moment this is allowed however we can be more strict if needed205        // there is not much sense in creating a spy of an interface206        Mockito.mock(IMethods.class, Mockito.withSettings().useConstructor());207        Mockito.spy(IMethods.class);208    }209    @Test210    public void prevents_across_jvm_serialization_with_constructor() {211        try {212            // when213            Mockito.mock(CreatingMocksWithConstructorTest.AbstractMessage.class, Mockito.withSettings().useConstructor().serializable(SerializableMode.ACROSS_CLASSLOADERS));214            // then215            Assert.fail();216        } catch (MockitoException e) {217            Assert.assertEquals((("Mocks instantiated with constructor cannot be combined with " + (SerializableMode.ACROSS_CLASSLOADERS)) + " serialization mode."), e.getMessage());218        }219    }220    abstract static class AbstractThing {221        abstract String name();222        String fullName() {223            return "abstract " + (name());224        }225    }226    @Test227    public void abstract_method_returns_default() {228        CreatingMocksWithConstructorTest.AbstractThing thing = Mockito.spy(CreatingMocksWithConstructorTest.AbstractThing.class);229        Assert.assertEquals("abstract null", thing.fullName());230    }231    @Test232    public void abstract_method_stubbed() {233        CreatingMocksWithConstructorTest.AbstractThing thing = Mockito.spy(CreatingMocksWithConstructorTest.AbstractThing.class);234        Mockito.when(thing.name()).thenReturn("me");235        Assert.assertEquals("abstract me", thing.fullName());236    }237    @Test238    public void interface_method_stubbed() {239        List<?> list = Mockito.spy(List.class);240        Mockito.when(list.size()).thenReturn(12);241        Assert.assertEquals(12, list.size());242    }243    @Test244    public void calls_real_interface_method() {245        List list = Mockito.mock(List.class, Mockito.withSettings().defaultAnswer(Mockito.CALLS_REAL_METHODS));246        Assert.assertNull(list.get(1));247    }248    @Test249    public void handles_bridge_methods_correctly() {250        CreatingMocksWithConstructorTest.SomeConcreteClass<Integer> testBug = Mockito.spy(new CreatingMocksWithConstructorTest.SomeConcreteClass<Integer>());251        Assert.assertEquals("value", testBug.getValue(0));252    }253    public abstract class SomeAbstractClass<T> {254        protected abstract String getRealValue(T value);255        public String getValue(T value) {256            return getRealValue(value);257        }258    }259    public class SomeConcreteClass<T extends Number> extends CreatingMocksWithConstructorTest.SomeAbstractClass<T> {260        @Override261        protected String getRealValue(T value) {262            return "value";263        }264    }265    private static class AmbiguousWithPrimitive {266        public AmbiguousWithPrimitive(String s, int i) {267            data = s;268        }269        public AmbiguousWithPrimitive(Object o, int i) {270            data = "just an object";271        }272        private String data;273        public String getData() {274            return data;275        }276    }277    @Test278    public void can_spy_ambiguius_constructor_with_primitive() {279        CreatingMocksWithConstructorTest.AmbiguousWithPrimitive mock = Mockito.mock(CreatingMocksWithConstructorTest.AmbiguousWithPrimitive.class, Mockito.withSettings().useConstructor("String", 7).defaultAnswer(Mockito.CALLS_REAL_METHODS));280        Assert.assertEquals("String", mock.getData());281    }282}...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!!
