Best Mockito code snippet using org.mockito.internal.MockitoCore.mockStatic
Source:Mockito.java
...1544 * In the following example, the <code>Foo</code> type's static method would return <code>foo</code> unless mocked:1545 *1546 * <pre class="code"><code class="java">1547 * assertEquals("foo", Foo.method());1548 * try (MockedStatic<Foo> mocked = mockStatic(Foo.class)) {1549 * mocked.when(Foo::method).thenReturn("bar");1550 * assertEquals("bar", Foo.method());1551 * mocked.verify(Foo::method);1552 * }1553 * assertEquals("foo", Foo.method());1554 * </code></pre>1555 *1556 * Due to the defined scope of the static mock, it returns to its original behavior once the scope is released. To define mock1557 * behavior and to verify static method invocations, use the <code>MockedStatic</code> that is returned.1558 * <p>1559 *1560 * <h3 id="49">49. <a class="meaningful_link" href="#mocked_construction" name="mocked_construction">Mocking object construction</a> (since 3.5.0)</h3>1561 *1562 * When using the <a href="#0.2">inline mock maker</a>, it is possible to generate mocks on constructor invocations within the current1563 * thread and a user-defined scope. This way, Mockito assures that concurrently and sequentially running tests do not interfere.1564 *1565 * To make sure a constructor mocks remain temporary, it is recommended to define the scope within a try-with-resources construct.1566 * In the following example, the <code>Foo</code> type's construction would generate a mock:1567 *1568 * <pre class="code"><code class="java">1569 * assertEquals("foo", new Foo().method());1570 * try (MockedConstruction<Foo> mocked = mockConstruction(Foo.class)) {1571 * Foo foo = new Foo();1572 * when(foo.method()).thenReturn("bar");1573 * assertEquals("bar", foo.method());1574 * verify(foo).method();1575 * }1576 * assertEquals("foo", new Foo().method());1577 * </code></pre>1578 *1579 * Due to the defined scope of the mocked construction, object construction returns to its original behavior once the scope is1580 * released. To define mock behavior and to verify method invocations, use the <code>MockedConstruction</code> that is returned.1581 * <p>1582 *1583 * <h3 id="50">50. <a class="meaningful_link" href="#proxy_mock_maker" name="mocked_construction">Avoiding code generation when only interfaces are mocked</a> (since 3.12.2)</h3>1584 *1585 * The JVM offers the {@link java.lang.reflect.Proxy} facility for creating dynamic proxies of interface types. For most applications, Mockito1586 * must be capable of mocking classes as supported by the default mock maker, or even final classes, as supported by the inline mock maker. To1587 * create such mocks, Mockito requires to setup diverse JVM facilities and must apply code generation. If only interfaces are supposed to be1588 * mocked, one can however choose to use a {@link org.mockito.internal.creation.proxy.ProxyMockMaker} that is based on the {@link java.lang.reflect.Proxy}1589 * API which avoids diverse overhead of the other mock makers but also limits mocking to interfaces.1590 *1591 * This mock maker can be activated explicitly by the mockito extension mechanism, just create in the classpath a file1592 * <code>/mockito-extensions/org.mockito.plugins.MockMaker</code> containing the value <code>mock-maker-proxy</code>.1593 *1594 * <p>1595 */1596@CheckReturnValue1597@SuppressWarnings("unchecked")1598public class Mockito extends ArgumentMatchers {1599 static final MockitoCore MOCKITO_CORE = new MockitoCore();1600 /**1601 * The default <code>Answer</code> of every mock <b>if</b> the mock was not stubbed.1602 *1603 * Typically it just returns some empty value.1604 * <p>1605 * {@link Answer} can be used to define the return values of unstubbed invocations.1606 * <p>1607 * This implementation first tries the global configuration and if there is no global configuration then1608 * it will use a default answer that returns zeros, empty collections, nulls, etc.1609 */1610 public static final Answer<Object> RETURNS_DEFAULTS = Answers.RETURNS_DEFAULTS;1611 /**1612 * Optional <code>Answer</code> to be used with {@link Mockito#mock(Class, Answer)}.1613 * <p>1614 * {@link Answer} can be used to define the return values of unstubbed invocations.1615 * <p>1616 * This implementation can be helpful when working with legacy code.1617 * Unstubbed methods often return null. If your code uses the object returned by an unstubbed call you get a NullPointerException.1618 * This implementation of Answer <b>returns SmartNull instead of null</b>.1619 * <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.1620 * <p>1621 * <code>ReturnsSmartNulls</code> first tries to return ordinary values (zeros, empty collections, empty string, etc.)1622 * then it tries to return SmartNull. If the return type is final then plain <code>null</code> is returned.1623 * <p>1624 * Example:1625 * <pre class="code"><code class="java">1626 * Foo mock = mock(Foo.class, RETURNS_SMART_NULLS);1627 *1628 * //calling unstubbed method here:1629 * Stuff stuff = mock.getStuff();1630 *1631 * //using object returned by unstubbed call:1632 * stuff.doSomething();1633 *1634 * //Above doesn't yield NullPointerException this time!1635 * //Instead, SmartNullPointerException is thrown.1636 * //Exception's cause links to unstubbed <i>mock.getStuff()</i> - just click on the stack trace.1637 * </code></pre>1638 */1639 public static final Answer<Object> RETURNS_SMART_NULLS = Answers.RETURNS_SMART_NULLS;1640 /**1641 * Optional <code>Answer</code> to be used with {@link Mockito#mock(Class, Answer)}1642 * <p>1643 * {@link Answer} can be used to define the return values of unstubbed invocations.1644 * <p>1645 * This implementation can be helpful when working with legacy code.1646 * <p>1647 * ReturnsMocks first tries to return ordinary values (zeros, empty collections, empty string, etc.)1648 * then it tries to return mocks. If the return type cannot be mocked (e.g. is final) then plain <code>null</code> is returned.1649 * <p>1650 */1651 public static final Answer<Object> RETURNS_MOCKS = Answers.RETURNS_MOCKS;1652 /**1653 * Optional <code>Answer</code> to be used with {@link Mockito#mock(Class, Answer)}.1654 * <p>1655 * Example that shows how deep stub works:1656 * <pre class="code"><code class="java">1657 * Foo mock = mock(Foo.class, RETURNS_DEEP_STUBS);1658 *1659 * // note that we're stubbing a chain of methods here: getBar().getName()1660 * when(mock.getBar().getName()).thenReturn("deep");1661 *1662 * // note that we're chaining method calls: getBar().getName()1663 * assertEquals("deep", mock.getBar().getName());1664 * </code></pre>1665 * </p>1666 *1667 * <p>1668 * <strong>WARNING: </strong>1669 * This feature should rarely be required for regular clean code! Leave it for legacy code.1670 * Mocking a mock to return a mock, to return a mock, (...), to return something meaningful1671 * hints at violation of Law of Demeter or mocking a value object (a well known anti-pattern).1672 * </p>1673 *1674 * <p>1675 * Good quote I've seen one day on the web: <strong>every time a mock returns a mock a fairy dies</strong>.1676 * </p>1677 *1678 * <p>1679 * Please note that this answer will return existing mocks that matches the stub. This1680 * behavior is ok with deep stubs and allows verification to work on the last mock of the chain.1681 * <pre class="code"><code class="java">1682 * when(mock.getBar(anyString()).getThingy().getName()).thenReturn("deep");1683 *1684 * mock.getBar("candy bar").getThingy().getName();1685 *1686 * assertSame(mock.getBar(anyString()).getThingy().getName(), mock.getBar(anyString()).getThingy().getName());1687 * verify(mock.getBar("candy bar").getThingy()).getName();1688 * verify(mock.getBar(anyString()).getThingy()).getName();1689 * </code></pre>1690 * </p>1691 *1692 * <p>1693 * Verification only works with the last mock in the chain. You can use verification modes.1694 * <pre class="code"><code class="java">1695 * when(person.getAddress(anyString()).getStreet().getName()).thenReturn("deep");1696 * when(person.getAddress(anyString()).getStreet(Locale.ITALIAN).getName()).thenReturn("deep");1697 * when(person.getAddress(anyString()).getStreet(Locale.CHINESE).getName()).thenReturn("deep");1698 *1699 * person.getAddress("the docks").getStreet().getName();1700 * person.getAddress("the docks").getStreet().getLongName();1701 * person.getAddress("the docks").getStreet(Locale.ITALIAN).getName();1702 * person.getAddress("the docks").getStreet(Locale.CHINESE).getName();1703 *1704 * // note that we are actually referring to the very last mock in the stubbing chain.1705 * InOrder inOrder = inOrder(1706 * person.getAddress("the docks").getStreet(),1707 * person.getAddress("the docks").getStreet(Locale.CHINESE),1708 * person.getAddress("the docks").getStreet(Locale.ITALIAN)1709 * );1710 * inOrder.verify(person.getAddress("the docks").getStreet(), times(1)).getName();1711 * inOrder.verify(person.getAddress("the docks").getStreet()).getLongName();1712 * inOrder.verify(person.getAddress("the docks").getStreet(Locale.ITALIAN), atLeast(1)).getName();1713 * inOrder.verify(person.getAddress("the docks").getStreet(Locale.CHINESE)).getName();1714 * </code></pre>1715 * </p>1716 *1717 * <p>1718 * How deep stub work internally?1719 * <pre class="code"><code class="java">1720 * //this:1721 * Foo mock = mock(Foo.class, RETURNS_DEEP_STUBS);1722 * when(mock.getBar().getName(), "deep");1723 *1724 * //is equivalent of1725 * Foo foo = mock(Foo.class);1726 * Bar bar = mock(Bar.class);1727 * when(foo.getBar()).thenReturn(bar);1728 * when(bar.getName()).thenReturn("deep");1729 * </code></pre>1730 * </p>1731 *1732 * <p>1733 * This feature will not work when any return type of methods included in the chain cannot be mocked1734 * (for example: is a primitive or a final class). This is because of java type system.1735 * </p>1736 */1737 public static final Answer<Object> RETURNS_DEEP_STUBS = Answers.RETURNS_DEEP_STUBS;1738 /**1739 * Optional <code>Answer</code> to be used with {@link Mockito#mock(Class, Answer)}1740 *1741 * <p>1742 * {@link Answer} can be used to define the return values of unstubbed invocations.1743 * <p>1744 * This implementation can be helpful when working with legacy code.1745 * When this implementation is used, unstubbed methods will delegate to the real implementation.1746 * This is a way to create a partial mock object that calls real methods by default.1747 * <p>1748 * As usual you are going to read <b>the partial mock warning</b>:1749 * Object oriented programming is more less tackling complexity by dividing the complexity into separate, specific, SRPy objects.1750 * How does partial mock fit into this paradigm? Well, it just doesn't...1751 * Partial mock usually means that the complexity has been moved to a different method on the same object.1752 * In most cases, this is not the way you want to design your application.1753 * <p>1754 * However, there are rare cases when partial mocks come handy:1755 * dealing with code you cannot change easily (3rd party interfaces, interim refactoring of legacy code etc.)1756 * However, I wouldn't use partial mocks for new, test-driven & well-designed code.1757 * <p>1758 * Example:1759 * <pre class="code"><code class="java">1760 * Foo mock = mock(Foo.class, CALLS_REAL_METHODS);1761 *1762 * // this calls the real implementation of Foo.getSomething()1763 * value = mock.getSomething();1764 *1765 * doReturn(fakeValue).when(mock).getSomething();1766 *1767 * // now fakeValue is returned1768 * value = mock.getSomething();1769 * </code></pre>1770 *1771 * <p>1772 * <u>Note 1:</u> Stubbing partial mocks using <code>when(mock.getSomething()).thenReturn(fakeValue)</code>1773 * syntax will call the real method. For partial mock it's recommended to use <code>doReturn</code> syntax.1774 * <p>1775 * <u>Note 2:</u> If the mock is serialized then deserialized, then this answer will not be able to understand1776 * generics metadata.1777 */1778 public static final Answer<Object> CALLS_REAL_METHODS = Answers.CALLS_REAL_METHODS;1779 /**1780 * Optional <code>Answer</code> to be used with {@link Mockito#mock(Class, Answer)}.1781 *1782 * Allows Builder mocks to return itself whenever a method is invoked that returns a Type equal1783 * to the class or a superclass.1784 *1785 * <p><b>Keep in mind this answer uses the return type of a method.1786 * If this type is assignable to the class of the mock, it will return the mock.1787 * Therefore if you have a method returning a superclass (for example {@code Object}) it will match and return the mock.</b></p>1788 *1789 * Consider a HttpBuilder used in a HttpRequesterWithHeaders.1790 *1791 * <pre class="code"><code class="java">1792 * public class HttpRequesterWithHeaders {1793 *1794 * private HttpBuilder builder;1795 *1796 * public HttpRequesterWithHeaders(HttpBuilder builder) {1797 * this.builder = builder;1798 * }1799 *1800 * public String request(String uri) {1801 * return builder.withUrl(uri)1802 * .withHeader("Content-type: application/json")1803 * .withHeader("Authorization: Bearer")1804 * .request();1805 * }1806 * }1807 *1808 * private static class HttpBuilder {1809 *1810 * private String uri;1811 * private List<String> headers;1812 *1813 * public HttpBuilder() {1814 * this.headers = new ArrayList<String>();1815 * }1816 *1817 * public HttpBuilder withUrl(String uri) {1818 * this.uri = uri;1819 * return this;1820 * }1821 *1822 * public HttpBuilder withHeader(String header) {1823 * this.headers.add(header);1824 * return this;1825 * }1826 *1827 * public String request() {1828 * return uri + headers.toString();1829 * }1830 * }1831 * </code></pre>1832 *1833 * The following test will succeed1834 *1835 * <pre><code>1836 * @Test1837 * public void use_full_builder_with_terminating_method() {1838 * HttpBuilder builder = mock(HttpBuilder.class, RETURNS_SELF);1839 * HttpRequesterWithHeaders requester = new HttpRequesterWithHeaders(builder);1840 * String response = "StatusCode: 200";1841 *1842 * when(builder.request()).thenReturn(response);1843 *1844 * assertThat(requester.request("URI")).isEqualTo(response);1845 * }1846 * </code></pre>1847 */1848 public static final Answer<Object> RETURNS_SELF = Answers.RETURNS_SELF;1849 /**1850 * Creates mock object of given class or interface.1851 * <p>1852 * See examples in javadoc for {@link Mockito} class1853 *1854 * @param classToMock class or interface to mock1855 * @return mock object1856 */1857 public static <T> T mock(Class<T> classToMock) {1858 return mock(classToMock, withSettings());1859 }1860 /**1861 * Specifies mock name. Naming mocks can be helpful for debugging - the name is used in all verification errors.1862 * <p>1863 * Beware that naming mocks is not a solution for complex code which uses too many mocks or collaborators.1864 * <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.1865 * <p>1866 * <b>If you use <code>@Mock</code> annotation then you've got naming mocks for free!</b> <code>@Mock</code> uses field name as mock name. {@link Mock Read more.}1867 * <p>1868 *1869 * See examples in javadoc for {@link Mockito} class1870 *1871 * @param classToMock class or interface to mock1872 * @param name of the mock1873 * @return mock object1874 */1875 public static <T> T mock(Class<T> classToMock, String name) {1876 return mock(classToMock, withSettings().name(name).defaultAnswer(RETURNS_DEFAULTS));1877 }1878 /**1879 * Returns a MockingDetails instance that enables inspecting a particular object for Mockito related information.1880 * Can be used to find out if given object is a Mockito mock1881 * or to find out if a given mock is a spy or mock.1882 * <p>1883 * In future Mockito versions MockingDetails may grow and provide other useful information about the mock,1884 * e.g. invocations, stubbing info, etc.1885 *1886 * @param toInspect - object to inspect. null input is allowed.1887 * @return A {@link org.mockito.MockingDetails} instance.1888 * @since 1.9.51889 */1890 public static MockingDetails mockingDetails(Object toInspect) {1891 return MOCKITO_CORE.mockingDetails(toInspect);1892 }1893 /**1894 * Creates mock with a specified strategy for its answers to interactions.1895 * It's quite an advanced feature and typically you don't need it to write decent tests.1896 * However it can be helpful when working with legacy systems.1897 * <p>1898 * It is the default answer so it will be used <b>only when you don't</b> stub the method call.1899 *1900 * <pre class="code"><code class="java">1901 * Foo mock = mock(Foo.class, RETURNS_SMART_NULLS);1902 * Foo mockTwo = mock(Foo.class, new YourOwnAnswer());1903 * </code></pre>1904 *1905 * <p>See examples in javadoc for {@link Mockito} class</p>1906 *1907 * @param classToMock class or interface to mock1908 * @param defaultAnswer default answer for unstubbed methods1909 *1910 * @return mock object1911 */1912 public static <T> T mock(Class<T> classToMock, Answer defaultAnswer) {1913 return mock(classToMock, withSettings().defaultAnswer(defaultAnswer));1914 }1915 /**1916 * Creates a mock with some non-standard settings.1917 * <p>1918 * The number of configuration points for a mock grows1919 * so we need a fluent way to introduce new configuration without adding more and more overloaded Mockito.mock() methods.1920 * Hence {@link MockSettings}.1921 * <pre class="code"><code class="java">1922 * Listener mock = mock(Listener.class, withSettings()1923 * .name("firstListner").defaultBehavior(RETURNS_SMART_NULLS));1924 * );1925 * </code></pre>1926 * <b>Use it carefully and occasionally</b>. What might be reason your test needs non-standard mocks?1927 * Is the code under test so complicated that it requires non-standard mocks?1928 * Wouldn't you prefer to refactor the code under test so it is testable in a simple way?1929 * <p>1930 * See also {@link Mockito#withSettings()}1931 * <p>1932 * See examples in javadoc for {@link Mockito} class1933 *1934 * @param classToMock class or interface to mock1935 * @param mockSettings additional mock settings1936 * @return mock object1937 */1938 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 public static <T> T spy(T object) {2021 return MOCKITO_CORE.mock(2022 (Class<T>) object.getClass(),2023 withSettings().spiedInstance(object).defaultAnswer(CALLS_REAL_METHODS));2024 }2025 /**2026 * Please refer to the documentation of {@link #spy(Object)}.2027 * Overusing spies hints at code design smells.2028 * <p>2029 * This method, in contrast to the original {@link #spy(Object)}, creates a spy based on class instead of an object.2030 * Sometimes it is more convenient to create spy based on the class and avoid providing an instance of a spied object.2031 * This is particularly useful for spying on abstract classes because they cannot be instantiated.2032 * See also {@link MockSettings#useConstructor(Object...)}.2033 * <p>2034 * Examples:2035 * <pre class="code"><code class="java">2036 * SomeAbstract spy = spy(SomeAbstract.class);2037 *2038 * //Robust API, via settings builder:2039 * OtherAbstract spy = mock(OtherAbstract.class, withSettings()2040 * .useConstructor().defaultAnswer(CALLS_REAL_METHODS));2041 *2042 * //Mocking a non-static inner abstract class:2043 * InnerAbstract spy = mock(InnerAbstract.class, withSettings()2044 * .useConstructor().outerInstance(outerInstance).defaultAnswer(CALLS_REAL_METHODS));2045 * </code></pre>2046 *2047 * @param classToSpy the class to spy2048 * @param <T> type of the spy2049 * @return a spy of the provided class2050 * @since 1.10.122051 */2052 public static <T> T spy(Class<T> classToSpy) {2053 return MOCKITO_CORE.mock(2054 classToSpy, withSettings().useConstructor().defaultAnswer(CALLS_REAL_METHODS));2055 }2056 /**2057 * Creates a thread-local mock controller for all static methods of the given class or interface.2058 * The returned object's {@link MockedStatic#close()} method must be called upon completing the2059 * test or the mock will remain active on the current thread.2060 * <p>2061 * <b>Note</b>: We recommend against mocking static methods of classes in the standard library or2062 * classes used by custom class loaders used to executed the block with the mocked class. A mock2063 * maker might forbid mocking static methods of know classes that are known to cause problems.2064 * Also, if a static method is a JVM-intrinsic, it cannot typically be mocked even if not2065 * explicitly forbidden.2066 * <p>2067 * See examples in javadoc for {@link Mockito} class2068 *2069 * @param classToMock class or interface of which static mocks should be mocked.2070 * @return mock controller2071 */2072 public static <T> MockedStatic<T> mockStatic(Class<T> classToMock) {2073 return mockStatic(classToMock, withSettings());2074 }2075 /**2076 * Creates a thread-local mock controller for all static methods of the given class or interface.2077 * The returned object's {@link MockedStatic#close()} method must be called upon completing the2078 * test or the mock will remain active on the current thread.2079 * <p>2080 * <b>Note</b>: We recommend against mocking static methods of classes in the standard library or2081 * classes used by custom class loaders used to executed the block with the mocked class. A mock2082 * maker might forbid mocking static methods of know classes that are known to cause problems.2083 * Also, if a static method is a JVM-intrinsic, it cannot typically be mocked even if not2084 * explicitly forbidden.2085 * <p>2086 * See examples in javadoc for {@link Mockito} class2087 *2088 * @param classToMock class or interface of which static mocks should be mocked.2089 * @param defaultAnswer the default answer when invoking static methods.2090 * @return mock controller2091 */2092 public static <T> MockedStatic<T> mockStatic(Class<T> classToMock, Answer defaultAnswer) {2093 return mockStatic(classToMock, withSettings().defaultAnswer(defaultAnswer));2094 }2095 /**2096 * Creates a thread-local mock controller for all static methods of the given class or interface.2097 * The returned object's {@link MockedStatic#close()} method must be called upon completing the2098 * test or the mock will remain active on the current thread.2099 * <p>2100 * <b>Note</b>: We recommend against mocking static methods of classes in the standard library or2101 * classes used by custom class loaders used to executed the block with the mocked class. A mock2102 * maker might forbid mocking static methods of know classes that are known to cause problems.2103 * Also, if a static method is a JVM-intrinsic, it cannot typically be mocked even if not2104 * explicitly forbidden.2105 * <p>2106 * See examples in javadoc for {@link Mockito} class2107 *2108 * @param classToMock class or interface of which static mocks should be mocked.2109 * @param name the name of the mock to use in error messages.2110 * @return mock controller2111 */2112 public static <T> MockedStatic<T> mockStatic(Class<T> classToMock, String name) {2113 return mockStatic(classToMock, withSettings().name(name));2114 }2115 /**2116 * Creates a thread-local mock controller for all static methods of the given class or interface.2117 * The returned object's {@link MockedStatic#close()} method must be called upon completing the2118 * test or the mock will remain active on the current thread.2119 * <p>2120 * <b>Note</b>: We recommend against mocking static methods of classes in the standard library or2121 * classes used by custom class loaders used to executed the block with the mocked class. A mock2122 * maker might forbid mocking static methods of know classes that are known to cause problems.2123 * Also, if a static method is a JVM-intrinsic, it cannot typically be mocked even if not2124 * explicitly forbidden.2125 * <p>2126 * See examples in javadoc for {@link Mockito} class2127 *2128 * @param classToMock class or interface of which static mocks should be mocked.2129 * @param mockSettings the settings to use where only name and default answer are considered.2130 * @return mock controller2131 */2132 public static <T> MockedStatic<T> mockStatic(Class<T> classToMock, MockSettings mockSettings) {2133 return MOCKITO_CORE.mockStatic(classToMock, mockSettings);2134 }2135 /**2136 * Creates a thread-local mock controller for all constructions of the given class.2137 * The returned object's {@link MockedConstruction#close()} method must be called upon completing the2138 * test or the mock will remain active on the current thread.2139 * <p>2140 * See examples in javadoc for {@link Mockito} class2141 *2142 * @param classToMock non-abstract class of which constructions should be mocked.2143 * @param defaultAnswer the default answer for the first created mock.2144 * @param additionalAnswers the default answer for all additional mocks. For any access mocks, the2145 * last answer is used. If this array is empty, the {@code defaultAnswer} is used.2146 * @return mock controller2147 */...
Source:MockitoCore.java
...55 T mock = createMock(creationSettings);56 mockingProgress().mockingStarted(mock, creationSettings);57 return mock;58 }59 public <T> MockedStatic<T> mockStatic(Class<T> classToMock, MockSettings settings) {60 if (!MockSettingsImpl.class.isInstance(settings)) {61 throw new IllegalArgumentException(62 "Unexpected implementation of '"63 + settings.getClass().getCanonicalName()64 + "'\n"65 + "At the moment, you cannot provide your own implementations of that class.");66 }67 MockSettingsImpl impl = MockSettingsImpl.class.cast(settings);68 MockCreationSettings<T> creationSettings = impl.buildStatic(classToMock);69 MockMaker.StaticMockControl<T> control = createStaticMock(classToMock, creationSettings);70 control.enable();71 mockingProgress().mockingStarted(classToMock, creationSettings);72 return new MockedStaticImpl<>(control);73 }...
Source:MockingFrameworkReporterFactoryImpl.java
...57// "For example:",58// " @PrepareForTest( { StaticService.class }) ",59// " TestClass{",60// " public void testMethod(){",61// " PowerMockito.mockStatic(StaticService.class);",62// " when(StaticService.say()).thenReturn(expected);",63// " }",64// " }",65// "",66// "Also, this error might show up because:",67// "1. inside when() you don't call method on mock but on some other object.",68// "2. inside when() you don't call static method, but class has not been prepared.",69// ""70// ));71// }72//73// }74}...
mockStatic
Using AI Code Generation
1import org.junit.Test;2import org.junit.runner.RunWith;3import org.mockito.Mock;4import org.mockito.Mockito;5import org.mockito.runners.MockitoJUnitRunner;6import static org.junit.Assert.assertEquals;7import static org.mockito.Mockito.mock;8import static org.mockito.Mockito.when;9@RunWith(MockitoJUnitRunner.class)10public class MockitoCoreTest {11 private SomeClass mock;12 public void testMockStaticMethod() {13 when(mock.getSomeString()).thenReturn("Hello World");14 assertEquals("Hello World", mock.getSomeString());15 }16}
mockStatic
Using AI Code Generation
1import static org.mockito.Mockito.mockStatic;2public class 1 {3 public static void main(String[] args) {4 mockStatic(MockitoCore.class);5 }6}7import static org.mockito.Mockito.mockStatic;8public class 2 {9 public static void main(String[] args) {10 mockStatic(MockitoCore.class);11 }12}13import static org.mockito.Mockito.mockStatic;14public class 3 {15 public static void main(String[] args) {16 mockStatic(MockitoCore.class);17 }18}19import static org.mockito.Mockito.mockStatic;20public class 4 {21 public static void main(String[] args) {22 mockStatic(MockitoCore.class);23 }24}25import static org.mockito.Mockito.mockStatic;26public class 5 {27 public static void main(String[] args) {28 mockStatic(MockitoCore.class);29 }30}31import static org.mockito.Mockito.mockStatic;32public class 6 {33 public static void main(String[] args) {34 mockStatic(MockitoCore.class);35 }36}37import static org.mockito.Mockito.mockStatic;38public class 7 {39 public static void main(String[] args) {40 mockStatic(MockitoCore.class);41 }42}43import static org.mockito.Mockito.mockStatic;44public class 8 {45 public static void main(String[] args) {46 mockStatic(MockitoCore.class);47 }48}49import static org.mockito.Mockito.mockStatic;50public class 9 {51 public static void main(String[] args) {52 mockStatic(MockitoCore.class);53 }54}
mockStatic
Using AI Code Generation
1import org.mockito.Mockito;2import org.mockito.MockitoAnnotations;3import org.mockito.internal.MockitoCore;4import org.mockito.internal.util.reflection.Whitebox;5import org.mockito.invocation.Invocation;6import org.mockito.invocation.MockHandler;7import org.mockito.invocation.MockHandlerFactory;8import org.mockito.mock.MockCreationSettings;9import org.mockito.plugins.MockMaker;10import static org.mockito.Mockito.mock;11import static org.mockito.Mockito.mockStatic;12import static org.mockito.Mockito.when;13public class Test {14 public void testMockStatic() {15 mockStatic(Mockito.class);16 }17}18import org.mockito.Mockito;19import org.mockito.MockitoAnnotations;20import org.mockito.internal.MockitoCore;21import org.mockito.internal.util.reflection.Whitebox;22import org.mockito.invocation.Invocation;23import org.mockito.invocation.MockHandler;24import org.mockito.invocation.MockHandlerFactory;25import org.mockito.mock.MockCreationSettings;26import org.mockito.plugins.MockMaker;27import static org.mockito.Mockito.mock;28import static org.mockito.Mockito.mockStatic;29import static org.mockito.Mockito.when;30public class Test {31 public void testMockStatic() {32 mockStatic(MockitoCore.class);33 }34}35 at org.mockito.internal.util.reflection.WhiteboxImpl.invokeMethod(WhiteboxImpl.java:129)36 at org.mockito.internal.util.reflection.WhiteboxImpl.invokeMethod(WhiteboxImpl.java:77)37 at org.mockito.internal.util.reflection.Whitebox.invokeMethod(Whitebox.java:126)38 at org.mockito.internal.util.reflection.Whitebox.invokeMethod(Whitebox.java:103)39 at org.mockito.internal.util.reflection.Whitebox.invokeMethod(Whitebox.java:98)40 at org.mockito.internal.util.MockUtil.getHandler(MockUtil.java:65)41 at org.mockito.internal.util.MockUtil.getMockSettings(MockUtil.java:71)42 at org.mockito.internal.MockitoCore.mock(MockitoCore.java:55)43 at org.mockito.Mockito.mock(Mockito.java:1838)44 at org.mockito.Mockito.mock(Mockito.java:1748)45 at org.mockito.Mockito.mockStatic(Mockito.java:2205)46 at Test.testMockStatic(Test.java:21)
mockStatic
Using AI Code Generation
1package org.mockito.internal;2import org.mockito.internal.MockitoCore;3import org.mockito.internal.creation.MockSettingsImpl;4import org.mockito.internal.progress.MockingProgress;5import org.mockito.internal.progress.ThreadSafeMockingProgress;6import org.mockito.internal.stubbing.answers.Returns;7import org.mockito.internal.util.MockUtil;8import org.mockito.mock.MockCreationSettings;9import org.mockito.mock.MockName;10import org.mockito.stubbing.Answer;11import org.mockito.stubbing.Stubber;12import org.mockito.verification.VerificationMode;13import static org.mockito.Mockito.*;14import static org.mockito.Mockito.mock;15import static org.mockito.Mockito.withSettings;16import static org.mockito.Mockito.mockingDetails;17import static org.mockito.Mockito.mockStatic;18import static org.mockito.Mockito.verify;19import static org.mockito.Mockito.times;20import static org.mockito.Mockito.verifyNoMoreInteractions;21import static org.mockito.Mockito.verifyZeroInteractions;22import static org.mockito.Mockito.verifyNoInteractions;23import static org.mockito.Mockito.withSettings;24import static org.mockito.Mockito.lenient;25import static org.mockito.Mockito.reset;26import static org.mockito.Mockito.spy;27import static org.mockito.Mockito.doReturn;28import static org.mockito.Mockito.doThrow;29import static org.mockito.Mockito.doNothing;30import static org.mockito.Mockito.doAnswer;31import static org.mockito.Mockito.doCallRealMethod;32import static org.mockito.Mockito.after;33import static org.mockito.Mockito.timeout;34import static org.mockito.Mockito.never;35import static org.mockito.Mockito.only;36import static org.mockito.Mockito.inOrder;37import static org.mockito.Mockito.verifyNoMoreInteractions;38import static org.mockito.Mockito.verifyZeroInteractions;39import static org.mockito.Mockito.verifyNoInteractions;40import static org.mockito.Mockito.ignoreStubs;41import static org.mockito.Mockito.withSettings;42import static org.mockito.Mockito.lenient;43import static org.mockito.Mockito.reset;44import static org.mockito.Mockito.spy;45import static org.mockito.Mockito.doReturn;46import static org.mockito.Mockito.doThrow;47import static org.mockito.Mockito.doNothing;48import static org.mockito.Mockito.doAnswer;49import static org.mockito.Mockito.doCallRealMethod;50import static org.mockito.Mockito.after;51import static org.mockito.Mockito.timeout;52import static org.mockito.Mockito.never;53import static org.mockito.Mockito.only;54import static org.mockito.Mockito.inOrder;55import static org.mockito.Mockito.verifyNoMoreInteractions;56import static org.mockito.Mockito.verifyZeroInteractions;57import static org.mockito.Mockito.verifyNoInteractions;58import static org.mockito.Mockito.ignoreStubs;59import static org.mockito.Mockito.withSettings;60import static org.mockito.Mockito.lenient;61import static
mockStatic
Using AI Code Generation
1package com.journaldev.mockito;2import static org.mockito.Mockito.mockStatic;3import java.util.List;4public class MockitoMockStaticExample {5 public static void main(String[] args) {6 List<String> listMock = mockStatic(List.class);7 System.out.println(listMock);8 }9}10Mockito mockStatic() Method11Mockito mockStatic() Example12package com.journaldev.mockito;13import static org.mockito.Mockito.mockStatic;14import java.util.List;15public class MockitoMockStaticExample {16 public static void main(String[] args) {17 List<String> listMock = mockStatic(List.class);18 System.out.println(listMock);19 }20}21Mockito mockStatic() Example with verify22package com.journaldev.mockito;23import static org.mockito.Mockito.mockStatic;24import static org.mockito.Mockito.verify;25import java.util.List;26public class MockitoMockStaticExample {27 public static void main(String[] args) {28 List<String> listMock = mockStatic(List.class);29 listMock.add("abc");30 verify(listMock).add("abc");31 }32}33-> at com.journaldev.mockito.MockitoMockStaticExample.main(MockitoMockStaticExample.java:11)34Mockito mockStatic() Example with verify35package com.journaldev.mockito;36import static org.mockito.Mockito.mockStatic;37import static org.mockito.Mockito.verify;38import java.util.List;39public class MockitoMockStaticExample {40 public static void main(String[] args) {41 List<String> listMock = mockStatic(List.class);42 listMock.add("abc");43 verify(listMock).add("abc");44 }45}
mockStatic
Using AI Code Generation
1package com.automationrhapsody.mockito;2import static org.mockito.Mockito.mockStatic;3import static org.mockito.Mockito.verify;4import static org.mockito.Mockito.when;5import org.junit.Test;6public class MockitoCoreMockStaticMethodTest {7 public void mockStaticMethod() {8 try (MockedStatic<MathUtils> mathUtils = mockStatic(MathUtils.class)) {9 mathUtils.when(MathUtils::add).thenReturn(5);10 int result = MathUtils.add(1, 2);11 mathUtils.verify(MathUtils::add);12 assertEquals(5, result);13 }14 }15}16package com.automationrhapsody.mockito;17import static org.mockito.Mockito.mockStatic;18import static org.mockito.Mockito.verify;19import static org.mockito.Mockito.when;20import org.junit.Test;21public class MockitoMockStaticMethodTest {22 public void mockStaticMethod() {23 try (MockedStatic<MathUtils> mathUtils = mockStatic(MathUtils.class)) {24 mathUtils.when(MathUtils::add).thenReturn(5);25 int result = MathUtils.add(1, 2);26 mathUtils.verify(MathUtils::add);27 assertEquals(5, result);28 }29 }30}31package com.automationrhapsody.mockito;32import static org.mockito.Mockito.mockStatic;33import static org.mockito.Mockito.verify;34import static org.mockito.Mockito.when;35import org.junit.Test;36public class MockitoMockStaticMethodTest {37 public void mockStaticMethod() {38 try (MockedStatic<MathUtils> mathUtils = mockStatic(MathUtils.class)) {39 mathUtils.when(MathUtils::add).thenReturn(5);40 int result = MathUtils.add(1, 2);41 mathUtils.verify(MathUtils::add);42 assertEquals(5, result);43 }44 }45}46package com.automationrhapsody.mockito;47import static org.mockito.Mockito.mockStatic;48import static org.mockito.Mockito.verify;49import static org.mockito.Mockito.when;50import org.junit.Test;
mockStatic
Using AI Code Generation
1package com.example;2import org.mockito.Mockito;3import static org.mockito.Mockito.mockStatic;4public class MockitoCoreMockStaticExample {5 public static void main(String[] args) {6 try (MockitoCoreMockStaticExample.MockedStatic mockedStatic = mockStatic(MockitoCoreMockStaticExample.class)) {7 System.out.println("Mocked static method");8 }9 }10}
mockStatic
Using AI Code Generation
1package org.mockito.internal;2import org.mockito.internal.MockitoCore;3import org.mockito.MockitoAnnotations;4import org.mockito.Mock;5import org.mockito.*;6import org.mockito.internal.*;7import org.mockito.internal.util.*;8import org.mockito.exceptions.*;9import org.mockito.internal.invocation.*;10import org.mockito.internal.creation.*;11import org.mockito.internal.stubbing.*;12import org.mockito.internal.verification.*;13import org.mockito.internal.util.reflection.*;14import org.mockito.internal.progress.*;15import org.mockito.internal.matchers.*;16import org.mockito.internal.debugging.*;17import org.mockito.internal.configuration.*;18import org.mockito.internal.listeners.*;19import org.mockito.stubbing.*;20import org.mockito.exceptions.misusing.*;21import org.mockito.exceptions.base.*;22import org.mockito.exceptions.verification.*;23import org.mockito.exceptions.verification.junit.ArgumentsAreDifferent;24import org.mockito.exceptions.verification.junit.WantedButNotInvoked;25import org.mockito.exceptions.verification.junit.NeverWantedButInvoked;26import org.mockito.exceptions.stacktrace.*;27import org.mockito.exceptions.reporting.*;28import org.mockito.internal.invocation.realmethod.*;29import org.mockito.internal.creation.instance.*;30import org.mockito.internal.creation.bytebuddy.*;31import org.mockito.internal.creation.jmock.*;32import org.mockito.internal.creation.jmock.ClassImposterizer;33import org.mockito.internal.creation.cglib.*;34import org.mockito.internal.creation.cglib.MockMaker;35import org.mockito.internal.creation.cglib.CGLIBHacker;36import org.mockito.internal.creation.cglib.ClassImposterizer;37import org.mockito.internal.creation.cglib.CGLIBHacker;38import org.mockito.internal.creation.cglib.CGLIBMockMaker;39import org.mockito.internal.creation.cglib.CGLIBProxyMaker;40import org.mockito.internal.creation.cglib.ClassImposterizer;41import org.mockito.internal.creation.cglib.CGLIBHacker;42import org.mockito.internal.creation.cglib.CGLIBMockMaker;43import org.mockito.internal.creation.cglib.CGLIBProxyMaker;44import org.mockito.internal.creation.cglib.ClassImposterizer;45import org.mockito.internal.creation.cglib.CGLIBHacker;46import org.mockito.internal.creation.cglib.CGLIBMockMaker;47import org.mockito.internal.creation.cglib.CGLIBProxyMaker;48import org.mockito.internal.creation.cglib.ClassImposterizer;49import org.mockito.internal.creation.cglib.CGLIBHacker;50import org.mockito.internal.creation.cglib.CGLIBMockMaker;51import org.mockito.internal.creation.cglib.CGLIBProxyMaker;52import org.mockito.internal.creation.cglib.ClassImposterizer;53import org.mockito.internal.creation.cglib.C
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!!