How to use mockConstruction method of org.mockito.internal.MockitoCore class

Best Mockito code snippet using org.mockito.internal.MockitoCore.mockConstruction

Source:Mockito.java Github

copy

Full Screen

...1573 * In the following example, the <code>Foo</code> type's construction would generate a mock:1574 *1575 * <pre class="code"><code class="java">1576 * assertEquals("foo", new Foo().method());1577 * try (MockedConstruction<Foo> mocked = mockConstruction(Foo.class)) {1578 * Foo foo = new Foo();1579 * when(foo.method()).thenReturn("bar");1580 * assertEquals("bar", foo.method());1581 * verify(foo).method();1582 * }1583 * assertEquals("foo", new Foo().method());1584 * </code></pre>1585 *1586 * Due to the defined scope of the mocked construction, object construction returns to its original behavior once the scope is1587 * released. To define mock behavior and to verify method invocations, use the <code>MockedConstruction</code> that is returned.1588 * <p>1589 */1590@SuppressWarnings("unchecked")1591public class Mockito extends ArgumentMatchers {1592 static final MockitoCore MOCKITO_CORE = new MockitoCore();1593 /**1594 * The default <code>Answer</code> of every mock <b>if</b> the mock was not stubbed.1595 *1596 * Typically it just returns some empty value.1597 * <p>1598 * {@link Answer} can be used to define the return values of unstubbed invocations.1599 * <p>1600 * This implementation first tries the global configuration and if there is no global configuration then1601 * it will use a default answer that returns zeros, empty collections, nulls, etc.1602 */1603 public static final Answer<Object> RETURNS_DEFAULTS = Answers.RETURNS_DEFAULTS;1604 /**1605 * Optional <code>Answer</code> to be used with {@link Mockito#mock(Class, Answer)}.1606 * <p>1607 * {@link Answer} can be used to define the return values of unstubbed invocations.1608 * <p>1609 * This implementation can be helpful when working with legacy code.1610 * Unstubbed methods often return null. If your code uses the object returned by an unstubbed call you get a NullPointerException.1611 * This implementation of Answer <b>returns SmartNull instead of null</b>.1612 * <code>SmartNull</code> gives nicer exception message than NPE because it points out the line where unstubbed method was called. You just click on the stack trace.1613 * <p>1614 * <code>ReturnsSmartNulls</code> first tries to return ordinary values (zeros, empty collections, empty string, etc.)1615 * then it tries to return SmartNull. If the return type is final then plain <code>null</code> is returned.1616 * <p>1617 * <code>ReturnsSmartNulls</code> will be probably the default return values strategy in Mockito 4.0.01618 * <p>1619 * Example:1620 * <pre class="code"><code class="java">1621 * Foo mock = mock(Foo.class, RETURNS_SMART_NULLS);1622 *1623 * //calling unstubbed method here:1624 * Stuff stuff = mock.getStuff();1625 *1626 * //using object returned by unstubbed call:1627 * stuff.doSomething();1628 *1629 * //Above doesn't yield NullPointerException this time!1630 * //Instead, SmartNullPointerException is thrown.1631 * //Exception's cause links to unstubbed <i>mock.getStuff()</i> - just click on the stack trace.1632 * </code></pre>1633 */1634 public static final Answer<Object> RETURNS_SMART_NULLS = Answers.RETURNS_SMART_NULLS;1635 /**1636 * Optional <code>Answer</code> to be used with {@link Mockito#mock(Class, Answer)}1637 * <p>1638 * {@link Answer} can be used to define the return values of unstubbed invocations.1639 * <p>1640 * This implementation can be helpful when working with legacy code.1641 * <p>1642 * ReturnsMocks first tries to return ordinary values (zeros, empty collections, empty string, etc.)1643 * then it tries to return mocks. If the return type cannot be mocked (e.g. is final) then plain <code>null</code> is returned.1644 * <p>1645 */1646 public static final Answer<Object> RETURNS_MOCKS = Answers.RETURNS_MOCKS;1647 /**1648 * Optional <code>Answer</code> to be used with {@link Mockito#mock(Class, Answer)}.1649 * <p>1650 * Example that shows how deep stub works:1651 * <pre class="code"><code class="java">1652 * Foo mock = mock(Foo.class, RETURNS_DEEP_STUBS);1653 *1654 * // note that we're stubbing a chain of methods here: getBar().getName()1655 * when(mock.getBar().getName()).thenReturn("deep");1656 *1657 * // note that we're chaining method calls: getBar().getName()1658 * assertEquals("deep", mock.getBar().getName());1659 * </code></pre>1660 * </p>1661 *1662 * <p>1663 * <strong>WARNING: </strong>1664 * This feature should rarely be required for regular clean code! Leave it for legacy code.1665 * Mocking a mock to return a mock, to return a mock, (...), to return something meaningful1666 * hints at violation of Law of Demeter or mocking a value object (a well known anti-pattern).1667 * </p>1668 *1669 * <p>1670 * Good quote I've seen one day on the web: <strong>every time a mock returns a mock a fairy dies</strong>.1671 * </p>1672 *1673 * <p>1674 * Please note that this answer will return existing mocks that matches the stub. This1675 * behavior is ok with deep stubs and allows verification to work on the last mock of the chain.1676 * <pre class="code"><code class="java">1677 * when(mock.getBar(anyString()).getThingy().getName()).thenReturn("deep");1678 *1679 * mock.getBar("candy bar").getThingy().getName();1680 *1681 * assertSame(mock.getBar(anyString()).getThingy().getName(), mock.getBar(anyString()).getThingy().getName());1682 * verify(mock.getBar("candy bar").getThingy()).getName();1683 * verify(mock.getBar(anyString()).getThingy()).getName();1684 * </code></pre>1685 * </p>1686 *1687 * <p>1688 * Verification only works with the last mock in the chain. You can use verification modes.1689 * <pre class="code"><code class="java">1690 * when(person.getAddress(anyString()).getStreet().getName()).thenReturn("deep");1691 * when(person.getAddress(anyString()).getStreet(Locale.ITALIAN).getName()).thenReturn("deep");1692 * when(person.getAddress(anyString()).getStreet(Locale.CHINESE).getName()).thenReturn("deep");1693 *1694 * person.getAddress("the docks").getStreet().getName();1695 * person.getAddress("the docks").getStreet().getLongName();1696 * person.getAddress("the docks").getStreet(Locale.ITALIAN).getName();1697 * person.getAddress("the docks").getStreet(Locale.CHINESE).getName();1698 *1699 * // note that we are actually referring to the very last mock in the stubbing chain.1700 * InOrder inOrder = inOrder(1701 * person.getAddress("the docks").getStreet(),1702 * person.getAddress("the docks").getStreet(Locale.CHINESE),1703 * person.getAddress("the docks").getStreet(Locale.ITALIAN)1704 * );1705 * inOrder.verify(person.getAddress("the docks").getStreet(), times(1)).getName();1706 * inOrder.verify(person.getAddress("the docks").getStreet()).getLongName();1707 * inOrder.verify(person.getAddress("the docks").getStreet(Locale.ITALIAN), atLeast(1)).getName();1708 * inOrder.verify(person.getAddress("the docks").getStreet(Locale.CHINESE)).getName();1709 * </code></pre>1710 * </p>1711 *1712 * <p>1713 * How deep stub work internally?1714 * <pre class="code"><code class="java">1715 * //this:1716 * Foo mock = mock(Foo.class, RETURNS_DEEP_STUBS);1717 * when(mock.getBar().getName(), "deep");1718 *1719 * //is equivalent of1720 * Foo foo = mock(Foo.class);1721 * Bar bar = mock(Bar.class);1722 * when(foo.getBar()).thenReturn(bar);1723 * when(bar.getName()).thenReturn("deep");1724 * </code></pre>1725 * </p>1726 *1727 * <p>1728 * This feature will not work when any return type of methods included in the chain cannot be mocked1729 * (for example: is a primitive or a final class). This is because of java type system.1730 * </p>1731 */1732 public static final Answer<Object> RETURNS_DEEP_STUBS = Answers.RETURNS_DEEP_STUBS;1733 /**1734 * Optional <code>Answer</code> to be used with {@link Mockito#mock(Class, Answer)}1735 *1736 * <p>1737 * {@link Answer} can be used to define the return values of unstubbed invocations.1738 * <p>1739 * This implementation can be helpful when working with legacy code.1740 * When this implementation is used, unstubbed methods will delegate to the real implementation.1741 * This is a way to create a partial mock object that calls real methods by default.1742 * <p>1743 * As usual you are going to read <b>the partial mock warning</b>:1744 * Object oriented programming is more less tackling complexity by dividing the complexity into separate, specific, SRPy objects.1745 * How does partial mock fit into this paradigm? Well, it just doesn't...1746 * Partial mock usually means that the complexity has been moved to a different method on the same object.1747 * In most cases, this is not the way you want to design your application.1748 * <p>1749 * However, there are rare cases when partial mocks come handy:1750 * dealing with code you cannot change easily (3rd party interfaces, interim refactoring of legacy code etc.)1751 * However, I wouldn't use partial mocks for new, test-driven & well-designed code.1752 * <p>1753 * Example:1754 * <pre class="code"><code class="java">1755 * Foo mock = mock(Foo.class, CALLS_REAL_METHODS);1756 *1757 * // this calls the real implementation of Foo.getSomething()1758 * value = mock.getSomething();1759 *1760 * doReturn(fakeValue).when(mock).getSomething();1761 *1762 * // now fakeValue is returned1763 * value = mock.getSomething();1764 * </code></pre>1765 *1766 * <p>1767 * <u>Note 1:</u> Stubbing partial mocks using <code>when(mock.getSomething()).thenReturn(fakeValue)</code>1768 * syntax will call the real method. For partial mock it's recommended to use <code>doReturn</code> syntax.1769 * <p>1770 * <u>Note 2:</u> If the mock is serialized then deserialized, then this answer will not be able to understand1771 * generics metadata.1772 */1773 public static final Answer<Object> CALLS_REAL_METHODS = Answers.CALLS_REAL_METHODS;1774 /**1775 * Optional <code>Answer</code> to be used with {@link Mockito#mock(Class, Answer)}.1776 *1777 * Allows Builder mocks to return itself whenever a method is invoked that returns a Type equal1778 * to the class or a superclass.1779 *1780 * <p><b>Keep in mind this answer uses the return type of a method.1781 * If this type is assignable to the class of the mock, it will return the mock.1782 * Therefore if you have a method returning a superclass (for example {@code Object}) it will match and return the mock.</b></p>1783 *1784 * Consider a HttpBuilder used in a HttpRequesterWithHeaders.1785 *1786 * <pre class="code"><code class="java">1787 * public class HttpRequesterWithHeaders {1788 *1789 * private HttpBuilder builder;1790 *1791 * public HttpRequesterWithHeaders(HttpBuilder builder) {1792 * this.builder = builder;1793 * }1794 *1795 * public String request(String uri) {1796 * return builder.withUrl(uri)1797 * .withHeader("Content-type: application/json")1798 * .withHeader("Authorization: Bearer")1799 * .request();1800 * }1801 * }1802 *1803 * private static class HttpBuilder {1804 *1805 * private String uri;1806 * private List&lt;String&gt; headers;1807 *1808 * public HttpBuilder() {1809 * this.headers = new ArrayList&lt;String&gt;();1810 * }1811 *1812 * public HttpBuilder withUrl(String uri) {1813 * this.uri = uri;1814 * return this;1815 * }1816 *1817 * public HttpBuilder withHeader(String header) {1818 * this.headers.add(header);1819 * return this;1820 * }1821 *1822 * public String request() {1823 * return uri + headers.toString();1824 * }1825 * }1826 * </code></pre>1827 *1828 * The following test will succeed1829 *1830 * <pre><code>1831 * &#064;Test1832 * public void use_full_builder_with_terminating_method() {1833 * HttpBuilder builder = mock(HttpBuilder.class, RETURNS_SELF);1834 * HttpRequesterWithHeaders requester = new HttpRequesterWithHeaders(builder);1835 * String response = "StatusCode: 200";1836 *1837 * when(builder.request()).thenReturn(response);1838 *1839 * assertThat(requester.request("URI")).isEqualTo(response);1840 * }1841 * </code></pre>1842 */1843 public static final Answer<Object> RETURNS_SELF = Answers.RETURNS_SELF;1844 /**1845 * Creates mock object of given class or interface.1846 * <p>1847 * See examples in javadoc for {@link Mockito} class1848 *1849 * @param classToMock class or interface to mock1850 * @return mock object1851 */1852 @CheckReturnValue1853 public static <T> T mock(Class<T> classToMock) {1854 return mock(classToMock, withSettings());1855 }1856 /**1857 * Specifies mock name. Naming mocks can be helpful for debugging - the name is used in all verification errors.1858 * <p>1859 * Beware that naming mocks is not a solution for complex code which uses too many mocks or collaborators.1860 * <b>If you have too many mocks then refactor the code</b> so that it's easy to test/debug without necessity of naming mocks.1861 * <p>1862 * <b>If you use <code>&#064;Mock</code> annotation then you've got naming mocks for free!</b> <code>&#064;Mock</code> uses field name as mock name. {@link Mock Read more.}1863 * <p>1864 *1865 * See examples in javadoc for {@link Mockito} class1866 *1867 * @param classToMock class or interface to mock1868 * @param name of the mock1869 * @return mock object1870 */1871 @CheckReturnValue1872 public static <T> T mock(Class<T> classToMock, String name) {1873 return mock(classToMock, withSettings().name(name).defaultAnswer(RETURNS_DEFAULTS));1874 }1875 /**1876 * Returns a MockingDetails instance that enables inspecting a particular object for Mockito related information.1877 * Can be used to find out if given object is a Mockito mock1878 * or to find out if a given mock is a spy or mock.1879 * <p>1880 * In future Mockito versions MockingDetails may grow and provide other useful information about the mock,1881 * e.g. invocations, stubbing info, etc.1882 *1883 * @param toInspect - object to inspect. null input is allowed.1884 * @return A {@link org.mockito.MockingDetails} instance.1885 * @since 1.9.51886 */1887 @CheckReturnValue1888 public static MockingDetails mockingDetails(Object toInspect) {1889 return MOCKITO_CORE.mockingDetails(toInspect);1890 }1891 /**1892 * Creates mock with a specified strategy for its answers to interactions.1893 * It's quite an advanced feature and typically you don't need it to write decent tests.1894 * However it can be helpful when working with legacy systems.1895 * <p>1896 * It is the default answer so it will be used <b>only when you don't</b> stub the method call.1897 *1898 * <pre class="code"><code class="java">1899 * Foo mock = mock(Foo.class, RETURNS_SMART_NULLS);1900 * Foo mockTwo = mock(Foo.class, new YourOwnAnswer());1901 * </code></pre>1902 *1903 * <p>See examples in javadoc for {@link Mockito} class</p>1904 *1905 * @param classToMock class or interface to mock1906 * @param defaultAnswer default answer for unstubbed methods1907 *1908 * @return mock object1909 */1910 @CheckReturnValue1911 public static <T> T mock(Class<T> classToMock, Answer defaultAnswer) {1912 return mock(classToMock, withSettings().defaultAnswer(defaultAnswer));1913 }1914 /**1915 * Creates a mock with some non-standard settings.1916 * <p>1917 * The number of configuration points for a mock grows1918 * so we need a fluent way to introduce new configuration without adding more and more overloaded Mockito.mock() methods.1919 * Hence {@link MockSettings}.1920 * <pre class="code"><code class="java">1921 * Listener mock = mock(Listener.class, withSettings()1922 * .name("firstListner").defaultBehavior(RETURNS_SMART_NULLS));1923 * );1924 * </code></pre>1925 * <b>Use it carefully and occasionally</b>. What might be reason your test needs non-standard mocks?1926 * Is the code under test so complicated that it requires non-standard mocks?1927 * Wouldn't you prefer to refactor the code under test so it is testable in a simple way?1928 * <p>1929 * See also {@link Mockito#withSettings()}1930 * <p>1931 * See examples in javadoc for {@link Mockito} class1932 *1933 * @param classToMock class or interface to mock1934 * @param mockSettings additional mock settings1935 * @return mock object1936 */1937 @CheckReturnValue1938 public static <T> T mock(Class<T> classToMock, MockSettings mockSettings) {1939 return MOCKITO_CORE.mock(classToMock, mockSettings);1940 }1941 /**1942 * Creates a spy of the real object. The spy calls <b>real</b> methods unless they are stubbed.1943 * <p>1944 * Real spies should be used <b>carefully and occasionally</b>, for example when dealing with legacy code.1945 * <p>1946 * As usual you are going to read <b>the partial mock warning</b>:1947 * Object oriented programming tackles complexity by dividing the complexity into separate, specific, SRPy objects.1948 * How does partial mock fit into this paradigm? Well, it just doesn't...1949 * Partial mock usually means that the complexity has been moved to a different method on the same object.1950 * In most cases, this is not the way you want to design your application.1951 * <p>1952 * However, there are rare cases when partial mocks come handy:1953 * dealing with code you cannot change easily (3rd party interfaces, interim refactoring of legacy code etc.)1954 * However, I wouldn't use partial mocks for new, test-driven & well-designed code.1955 * <p>1956 * Example:1957 *1958 * <pre class="code"><code class="java">1959 * List list = new LinkedList();1960 * List spy = spy(list);1961 *1962 * //optionally, you can stub out some methods:1963 * when(spy.size()).thenReturn(100);1964 *1965 * //using the spy calls <b>real</b> methods1966 * spy.add("one");1967 * spy.add("two");1968 *1969 * //prints "one" - the first element of a list1970 * System.out.println(spy.get(0));1971 *1972 * //size() method was stubbed - 100 is printed1973 * System.out.println(spy.size());1974 *1975 * //optionally, you can verify1976 * verify(spy).add("one");1977 * verify(spy).add("two");1978 * </code></pre>1979 *1980 * <h4>Important gotcha on spying real objects!</h4>1981 * <ol>1982 * <li>Sometimes it's impossible or impractical to use {@link Mockito#when(Object)} for stubbing spies.1983 * Therefore for spies it is recommended to always use <code>doReturn</code>|<code>Answer</code>|<code>Throw()</code>|<code>CallRealMethod</code>1984 * family of methods for stubbing. Example:1985 *1986 * <pre class="code"><code class="java">1987 * List list = new LinkedList();1988 * List spy = spy(list);1989 *1990 * //Impossible: real method is called so spy.get(0) throws IndexOutOfBoundsException (the list is yet empty)1991 * when(spy.get(0)).thenReturn("foo");1992 *1993 * //You have to use doReturn() for stubbing1994 * doReturn("foo").when(spy).get(0);1995 * </code></pre>1996 * </li>1997 *1998 * <li>Mockito <b>*does not*</b> delegate calls to the passed real instance, instead it actually creates a copy of it.1999 * So if you keep the real instance and interact with it, don't expect the spied to be aware of those interaction2000 * and their effect on real instance state.2001 * The corollary is that when an <b>*unstubbed*</b> method is called <b>*on the spy*</b> but <b>*not on the real instance*</b>,2002 * you won't see any effects on the real instance.</li>2003 *2004 * <li>Watch out for final methods.2005 * Mockito doesn't mock final methods so the bottom line is: when you spy on real objects + you try to stub a final method = trouble.2006 * Also you won't be able to verify those method as well.2007 * </li>2008 * </ol>2009 * <p>2010 * See examples in javadoc for {@link Mockito} class2011 *2012 * <p>Note that the spy won't have any annotations of the spied type, because CGLIB won't rewrite them.2013 * It may troublesome for code that rely on the spy to have these annotations.</p>2014 *2015 *2016 * @param object2017 * to spy on2018 * @return a spy of the real object2019 */2020 @CheckReturnValue2021 public static <T> T spy(T object) {2022 return MOCKITO_CORE.mock(2023 (Class<T>) object.getClass(),2024 withSettings().spiedInstance(object).defaultAnswer(CALLS_REAL_METHODS));2025 }2026 /**2027 * Please refer to the documentation of {@link #spy(Object)}.2028 * Overusing spies hints at code design smells.2029 * <p>2030 * This method, in contrast to the original {@link #spy(Object)}, creates a spy based on class instead of an object.2031 * Sometimes it is more convenient to create spy based on the class and avoid providing an instance of a spied object.2032 * This is particularly useful for spying on abstract classes because they cannot be instantiated.2033 * See also {@link MockSettings#useConstructor(Object...)}.2034 * <p>2035 * Examples:2036 * <pre class="code"><code class="java">2037 * SomeAbstract spy = spy(SomeAbstract.class);2038 *2039 * //Robust API, via settings builder:2040 * OtherAbstract spy = mock(OtherAbstract.class, withSettings()2041 * .useConstructor().defaultAnswer(CALLS_REAL_METHODS));2042 *2043 * //Mocking a non-static inner abstract class:2044 * InnerAbstract spy = mock(InnerAbstract.class, withSettings()2045 * .useConstructor().outerInstance(outerInstance).defaultAnswer(CALLS_REAL_METHODS));2046 * </code></pre>2047 *2048 * @param classToSpy the class to spy2049 * @param <T> type of the spy2050 * @return a spy of the provided class2051 * @since 1.10.122052 */2053 @Incubating2054 @CheckReturnValue2055 public static <T> T spy(Class<T> classToSpy) {2056 return MOCKITO_CORE.mock(2057 classToSpy, withSettings().useConstructor().defaultAnswer(CALLS_REAL_METHODS));2058 }2059 /**2060 * Creates a thread-local mock controller for all static methods of the given class or interface.2061 * The returned object's {@link MockedStatic#close()} method must be called upon completing the2062 * test or the mock will remain active on the current thread.2063 * <p>2064 * <b>Note</b>: We recommend against mocking static methods of classes in the standard library or2065 * classes used by custom class loaders used to executed the block with the mocked class. A mock2066 * maker might forbid mocking static methods of know classes that are known to cause problems.2067 * Also, if a static method is a JVM-intrinsic, it cannot typically be mocked even if not2068 * explicitly forbidden.2069 * <p>2070 * See examples in javadoc for {@link Mockito} class2071 *2072 * @param classToMock class or interface of which static mocks should be mocked.2073 * @return mock controller2074 */2075 @Incubating2076 @CheckReturnValue2077 public static <T> MockedStatic<T> mockStatic(Class<T> classToMock) {2078 return mockStatic(classToMock, withSettings());2079 }2080 /**2081 * Creates a thread-local mock controller for all static methods of the given class or interface.2082 * The returned object's {@link MockedStatic#close()} method must be called upon completing the2083 * test or the mock will remain active on the current thread.2084 * <p>2085 * <b>Note</b>: We recommend against mocking static methods of classes in the standard library or2086 * classes used by custom class loaders used to executed the block with the mocked class. A mock2087 * maker might forbid mocking static methods of know classes that are known to cause problems.2088 * Also, if a static method is a JVM-intrinsic, it cannot typically be mocked even if not2089 * explicitly forbidden.2090 * <p>2091 * See examples in javadoc for {@link Mockito} class2092 *2093 * @param classToMock class or interface of which static mocks should be mocked.2094 * @param defaultAnswer the default answer when invoking static methods.2095 * @return mock controller2096 */2097 @Incubating2098 @CheckReturnValue2099 public static <T> MockedStatic<T> mockStatic(Class<T> classToMock, Answer defaultAnswer) {2100 return mockStatic(classToMock, withSettings().defaultAnswer(defaultAnswer));2101 }2102 /**2103 * Creates a thread-local mock controller for all static methods of the given class or interface.2104 * The returned object's {@link MockedStatic#close()} method must be called upon completing the2105 * test or the mock will remain active on the current thread.2106 * <p>2107 * <b>Note</b>: We recommend against mocking static methods of classes in the standard library or2108 * classes used by custom class loaders used to executed the block with the mocked class. A mock2109 * maker might forbid mocking static methods of know classes that are known to cause problems.2110 * Also, if a static method is a JVM-intrinsic, it cannot typically be mocked even if not2111 * explicitly forbidden.2112 * <p>2113 * See examples in javadoc for {@link Mockito} class2114 *2115 * @param classToMock class or interface of which static mocks should be mocked.2116 * @param name the name of the mock to use in error messages.2117 * @return mock controller2118 */2119 @Incubating2120 @CheckReturnValue2121 public static <T> MockedStatic<T> mockStatic(Class<T> classToMock, String name) {2122 return mockStatic(classToMock, withSettings().name(name));2123 }2124 /**2125 * Creates a thread-local mock controller for all static methods of the given class or interface.2126 * The returned object's {@link MockedStatic#close()} method must be called upon completing the2127 * test or the mock will remain active on the current thread.2128 * <p>2129 * <b>Note</b>: We recommend against mocking static methods of classes in the standard library or2130 * classes used by custom class loaders used to executed the block with the mocked class. A mock2131 * maker might forbid mocking static methods of know classes that are known to cause problems.2132 * Also, if a static method is a JVM-intrinsic, it cannot typically be mocked even if not2133 * explicitly forbidden.2134 * <p>2135 * See examples in javadoc for {@link Mockito} class2136 *2137 * @param classToMock class or interface of which static mocks should be mocked.2138 * @param mockSettings the settings to use where only name and default answer are considered.2139 * @return mock controller2140 */2141 @Incubating2142 @CheckReturnValue2143 public static <T> MockedStatic<T> mockStatic(Class<T> classToMock, MockSettings mockSettings) {2144 return MOCKITO_CORE.mockStatic(classToMock, mockSettings);2145 }2146 /**2147 * Creates a thread-local mock controller for all constructions of the given class.2148 * The returned object's {@link MockedConstruction#close()} method must be called upon completing the2149 * test or the mock will remain active on the current thread.2150 * <p>2151 * See examples in javadoc for {@link Mockito} class2152 *2153 * @param classToMock non-abstract class of which constructions should be mocked.2154 * @param defaultAnswer the default answer for the first created mock.2155 * @param additionalAnswers the default answer for all additional mocks. For any access mocks, the2156 * last answer is used. If this array is empty, the {@code defaultAnswer} is used.2157 * @return mock controller2158 */2159 @Incubating2160 @CheckReturnValue2161 public static <T> MockedConstruction<T> mockConstructionWithAnswer(2162 Class<T> classToMock, Answer defaultAnswer, Answer... additionalAnswers) {2163 return mockConstruction(2164 classToMock,2165 context -> {2166 if (context.getCount() == 1 || additionalAnswers.length == 0) {2167 return withSettings().defaultAnswer(defaultAnswer);2168 } else if (context.getCount() >= additionalAnswers.length) {2169 return withSettings()2170 .defaultAnswer(additionalAnswers[additionalAnswers.length - 1]);2171 } else {2172 return withSettings()2173 .defaultAnswer(additionalAnswers[context.getCount() - 2]);2174 }2175 },2176 (mock, context) -> {});2177 }2178 /**2179 * Creates a thread-local mock controller for all constructions of the given class.2180 * The returned object's {@link MockedConstruction#close()} method must be called upon completing the2181 * test or the mock will remain active on the current thread.2182 * <p>2183 * See examples in javadoc for {@link Mockito} class2184 *2185 * @param classToMock non-abstract class of which constructions should be mocked.2186 * @return mock controller2187 */2188 @Incubating2189 @CheckReturnValue2190 public static <T> MockedConstruction<T> mockConstruction(Class<T> classToMock) {2191 return mockConstruction(classToMock, index -> withSettings(), (mock, context) -> {});2192 }2193 /**2194 * Creates a thread-local mock controller for all constructions of the given class.2195 * The returned object's {@link MockedConstruction#close()} method must be called upon completing the2196 * test or the mock will remain active on the current thread.2197 * <p>2198 * See examples in javadoc for {@link Mockito} class2199 *2200 * @param classToMock non-abstract class of which constructions should be mocked.2201 * @param mockInitializer a callback to prepare a mock's methods after its instantiation.2202 * @return mock controller2203 */2204 @Incubating2205 @CheckReturnValue2206 public static <T> MockedConstruction<T> mockConstruction(2207 Class<T> classToMock, MockedConstruction.MockInitializer<T> mockInitializer) {2208 return mockConstruction(classToMock, withSettings(), mockInitializer);2209 }2210 /**2211 * Creates a thread-local mock controller for all constructions of the given class.2212 * The returned object's {@link MockedConstruction#close()} method must be called upon completing the2213 * test or the mock will remain active on the current thread.2214 * <p>2215 * See examples in javadoc for {@link Mockito} class2216 *2217 * @param classToMock non-abstract class of which constructions should be mocked.2218 * @param mockSettings the mock settings to use.2219 * @return mock controller2220 */2221 @Incubating2222 @CheckReturnValue2223 public static <T> MockedConstruction<T> mockConstruction(2224 Class<T> classToMock, MockSettings mockSettings) {2225 return mockConstruction(classToMock, context -> mockSettings);2226 }2227 /**2228 * Creates a thread-local mock controller for all constructions of the given class.2229 * The returned object's {@link MockedConstruction#close()} method must be called upon completing the2230 * test or the mock will remain active on the current thread.2231 * <p>2232 * See examples in javadoc for {@link Mockito} class2233 *2234 * @param classToMock non-abstract class of which constructions should be mocked.2235 * @param mockSettingsFactory the mock settings to use.2236 * @return mock controller2237 */2238 @Incubating2239 @CheckReturnValue2240 public static <T> MockedConstruction<T> mockConstruction(2241 Class<T> classToMock,2242 Function<MockedConstruction.Context, MockSettings> mockSettingsFactory) {2243 return mockConstruction(classToMock, mockSettingsFactory, (mock, context) -> {});2244 }2245 /**2246 * Creates a thread-local mock controller for all constructions of the given class.2247 * The returned object's {@link MockedConstruction#close()} method must be called upon completing the2248 * test or the mock will remain active on the current thread.2249 * <p>2250 * See examples in javadoc for {@link Mockito} class2251 *2252 * @param classToMock non-abstract class of which constructions should be mocked.2253 * @param mockSettings the settings to use.2254 * @param mockInitializer a callback to prepare a mock's methods after its instantiation.2255 * @return mock controller2256 */2257 @Incubating2258 @CheckReturnValue2259 public static <T> MockedConstruction<T> mockConstruction(2260 Class<T> classToMock,2261 MockSettings mockSettings,2262 MockedConstruction.MockInitializer<T> mockInitializer) {2263 return mockConstruction(classToMock, index -> mockSettings, mockInitializer);2264 }2265 /**2266 * Creates a thread-local mock controller for all constructions of the given class.2267 * The returned object's {@link MockedConstruction#close()} method must be called upon completing the2268 * test or the mock will remain active on the current thread.2269 * <p>2270 * See examples in javadoc for {@link Mockito} class2271 *2272 * @param classToMock non-abstract class of which constructions should be mocked.2273 * @param mockSettingsFactory a function to create settings to use.2274 * @param mockInitializer a callback to prepare a mock's methods after its instantiation.2275 * @return mock controller2276 */2277 @Incubating2278 @CheckReturnValue2279 public static <T> MockedConstruction<T> mockConstruction(2280 Class<T> classToMock,2281 Function<MockedConstruction.Context, MockSettings> mockSettingsFactory,2282 MockedConstruction.MockInitializer<T> mockInitializer) {2283 return MOCKITO_CORE.mockConstruction(classToMock, mockSettingsFactory, mockInitializer);2284 }2285 /**2286 * Enables stubbing methods. Use it when you want the mock to return particular value when particular method is called.2287 * <p>2288 * Simply put: "<b>When</b> the x method is called <b>then</b> return y".2289 *2290 * <p>2291 * Examples:2292 *2293 * <pre class="code"><code class="java">2294 * <b>when</b>(mock.someMethod()).<b>thenReturn</b>(10);2295 *2296 * //you can use flexible argument matchers, e.g:2297 * when(mock.someMethod(<b>anyString()</b>)).thenReturn(10);...

Full Screen

Full Screen

Source:MockitoCore.java Github

copy

Full Screen

...70 control.enable();71 mockingProgress().mockingStarted(classToMock, creationSettings);72 return new MockedStaticImpl<>(control);73 }74 public <T> MockedConstruction<T> mockConstruction(75 Class<T> typeToMock,76 Function<MockedConstruction.Context, ? extends MockSettings> settingsFactory,77 MockedConstruction.MockInitializer<T> mockInitializer) {78 Function<MockedConstruction.Context, MockCreationSettings<T>> creationSettings =79 context -> {80 MockSettings value = settingsFactory.apply(context);81 if (!MockSettingsImpl.class.isInstance(value)) {82 throw new IllegalArgumentException(83 "Unexpected implementation of '"84 + value.getClass().getCanonicalName()85 + "'\n"86 + "At the moment, you cannot provide your own implementations of that class.");87 }88 MockSettingsImpl impl = MockSettingsImpl.class.cast(value);...

Full Screen

Full Screen

mockConstruction

Using AI Code Generation

copy

Full Screen

1import org.mockito.internal.MockitoCore;2import org.mockito.invocation.Invocation;3import org.mockito.invocation.MockHandler;4import org.mockito.stubbing.Answer;5import org.mockito.stubbing.Stubbing;6import org.mockito.verification.VerificationMode;7import org.mockito.verification.VerificationStrategy;8import org.mockito.verification.VerificationWithTimeout;9import org.mockito.verification.VerificationWrapper;10import org.mockito.internal.progress.MockingProgress;11import org.mockito.internal.progress.ThreadSafeMockingProgress;12import org.mockito.internal.invocation.InvocationMatcher;13import org.mockito.internal.invocation.InvocationBuilder;14import org.mockito.internal.invocation.InvocationImpl;15import org.mockito.internal.inv

Full Screen

Full Screen

mockConstruction

Using AI Code Generation

copy

Full Screen

1import org.mockito.internal.MockitoCore;2import org.mockito.MockSettings;3import org.mockito.Mock;4import org.mockito.Mockito;5import org.mockito.MockitoAnnotations;6import org.mockito.exceptions.base.MockitoException;7import org.mockito.internal.configuration.MockAnnotationProcessor;8import org.mockito.internal

Full Screen

Full Screen

mockConstruction

Using AI Code Generation

copy

Full Screen

1import org.mockito.MockSettings;2import org.mockito.Mockito;3import org.mockito.internal.MockitoCore;4import org.mockito.invocation.InvocationOnMock;5import org.mockito.stubbing.Answer;6import org.mockito.stubbing.Stubber;7import org.mockito.verification.VerificationMode;8import java.lang.reflect.Constructor;9import java.lang.reflect.Method;10import java.lang.reflect.Modifier;11import java.util.HashSet;12import java.util.Set;13import static org.mockito.Mockito.*;14public class MockitoCoreMockStaticMethods {15 public static void main(String[] args) {16 mockStaticMethods();17 }18 public static void mockStaticMethods() {19 MockitoCore core = new MockitoCore();20 core.mockStatic(StaticClass.class, withSettings().defaultAnswer(new Answer() {21 public Object answer(InvocationOnMock invocationOnMock) throws Throwable {22 return invocationOnMock.getMethod().getReturnType().newInstance();23 }24 }));25 }26}27public class StaticClass {28 public static int staticMethod() {29 return 0;30 }31}32 at org.mockito.internal.util.MockUtil.createMock(MockUtil.java:31)33 at org.mockito.internal.MockitoCore.mock(MockitoCore.java:60)34 at org.mockito.internal.MockitoCore.mock(MockitoCore.java:46)35 at MockitoCoreMockStaticMethods.mockStaticMethods(MockitoCoreMockStaticMethods.java:18)36 at MockitoCoreMockStaticMethods.main(MockitoCoreMockStaticMethods.java:11)37public class StaticClass {38 public static int staticMethod() {39 return 0;40 }41}42public class MockitoCoreMockStaticMethods {43 public static void main(String[] args) {44 mockStaticMethods();45 }46 public static void mockStaticMethods() {47 MockitoCore core = new MockitoCore();48 core.mockStatic(StaticClass.class, withSettings().defaultAnswer(new Answer() {49 public Object answer(InvocationOnMock invocationOnMock) throws Throwable {50 return invocationOnMock.getMethod().getReturnType().newInstance();51 }52 }));53 }54}

Full Screen

Full Screen

mockConstruction

Using AI Code Generation

copy

Full Screen

1package org.mockito.internal;2import org.mockito.internal.creation.MockSettingsImpl;3import org.mockito.internal.invocation.InvocationMatcher;4import org.mockito.internal.progress.MockingProgress;5import org.mockito.internal.progress.ThreadSafeMockingProgress;6import org.mockito.internal.stubbing.StubbedInvocationMatcher;7import org.mockito.invocation.Invocation;8import org.mockito.invocation.InvocationOnMock;9import org.mockito.invocation.MockHandler;10import org.mockito.mock.MockCreationSettings;11import org.mockito.stubbing.Answer;12import org.mockito.stubbing.Stubbing;13import java.lang.reflect.Constructor;14import java.util.List;15import static org.mockito.internal.progress.ThreadSafeMockingProgress.mockingProgress;16public class MockitoCore {17 public <T> T mock(Class<T> classToMock, MockCreationSettings<T> settings) {18 MockingProgress mockingProgress = mockingProgress();19 mockingProgress.validateState();20 MockHandler handler = new MockHandlerImpl<T>(settings);21 T mock = mockingProgress.mockingStarted(classToMock, settings, handler);22 mockingProgress.mockingFinished(mock, settings);23 return mock;24 }25 public <T> T mock(Class<T> classToMock, String name) {26 return mock(classToMock, new MockSettingsImpl<T>().name(name));27 }28 public <T> T mock(Class<T> classToMock, Answer defaultAnswer) {29 return mock(classToMock, new MockSettingsImpl<T>().defaultAnswer(defaultAnswer));30 }31 public <T> T mock(Class<T> classToMock) {32 return mock(classToMock, new MockSettingsImpl<T>());33 }34 public void verifyNoMoreInteractions(Object... mocks) {35 for (Object mock : mocks) {36 mockingProgress().verificationStarted(new InvocationMatcher(mock, null));37 }38 }39 public void verifyZeroInteractions(Object... mocks) {40 for (Object mock : mocks) {41 mockingProgress().verificationStarted(new InvocationMatcher(mock, null));42 }43 }44 public void verifyNoMoreInteractions(Object mock) {45 mockingProgress().verificationStarted(new InvocationMatcher(mock, null));46 }47 public void verifyZeroInteractions(Object mock) {48 mockingProgress().verificationStarted(new InvocationMatcher(mock, null));49 }50 public void verify(Object mock) {51 mockingProgress().verificationStarted(new InvocationMatcher(mock, null));52 }53 public void verify(Object mock, int

Full Screen

Full Screen

mockConstruction

Using AI Code Generation

copy

Full Screen

1package com.automationrhapsody.junitmockito;2import static org.mockito.Mockito.mockConstruction;3import java.time.LocalDateTime;4public class MockitoCoreMockConstructorExample {5 public static void main(String[] args) {6 try (MockedConstruction<LocalDateTime> mockedConstruction = mockConstruction(LocalDateTime.class)) {7 LocalDateTime.now();8 }9 }10}

Full Screen

Full Screen

mockConstruction

Using AI Code Generation

copy

Full Screen

1import static org.mockito.Mockito.mockConstruction;2import static org.mockito.Mockito.mockConstructionSettings;3import static org.mockito.Mockito.mockStatic;4import static org.mockito.Mockito.when;5import static org.mockito.Mockito.mock;6import static org.mockito.Mockito.withSettings;7import static org.mockito.Mockito.lenient;8import static org.mockito.Mockito.verify;9import static org.mockito.Mockito.times;10import static org.mockito.Mockito.any;11import static org.mockito.Mockito.doNothing;12import static org.mockito.Mockito.doReturn;13import static org.mockito.ArgumentMatchers.anyString;14import static org.mockito.ArgumentMatchers.anyInt;15import static org.mockito.ArgumentMatchers.anyBoolean;16import static org.mockito.ArgumentMatchers.anyLong;17import static org.mockito.ArgumentMatchers.anyList;18import static org.mockito.ArgumentMatchers.anyMap;19import static org.mockito.ArgumentMatchers.anySet;20import static org.mockito.ArgumentMatchers.anyCollection;21import static org.mockito.ArgumentMatchers.anyIterable;22import static org.mockito.ArgumentMatchers.anyObject;23import static org.mockito.ArgumentMatchers.anyVararg;24import static org.mockito.ArgumentMatchers.any;25import stat

Full Screen

Full Screen

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.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful