How to use Mockito class of org.mockito package

Best Mockito code snippet using org.mockito.Mockito

Source:OfficalTest_Part_1.java Github

copy

Full Screen

...3import org.mockito.ArgumentMatcher;4import org.mockito.InOrder;5import java.util.LinkedList;6import java.util.List;7import static org.mockito.Mockito.anyInt;8import static org.mockito.Mockito.anyObject;9import static org.mockito.Mockito.argThat;10import static org.mockito.Mockito.atLeast;11import static org.mockito.Mockito.atLeastOnce;12import static org.mockito.Mockito.atMost;13import static org.mockito.Mockito.doThrow;14import static org.mockito.Mockito.inOrder;15import static org.mockito.Mockito.mock;16import static org.mockito.Mockito.never;17import static org.mockito.Mockito.times;18import static org.mockito.Mockito.verify;19import static org.mockito.Mockito.verifyNoMoreInteractions;20import static org.mockito.Mockito.verifyZeroInteractions;21import static org.mockito.Mockito.when;22public class OfficalTest_Part_1 {23 /*24 * 关于默认值25 * 1、 默认情况下,对于所有的方法来说,都将有一个默认的值被返回,26 * 例如对于int\Integer来说是0,对于boolean\Boolean来说是false27 * 2、虽然默认值,可以通过代码进行覆盖,但是过多的覆盖的动作,将会产生更多的代码量28 * 3、一旦被复写之后,无论调用多少次,都将返回复写之后的值29 * 4、最后,存根数据是非常重要的,尤其是当时你使用相同的参数,调用的相同的方法修改默认的值时。30 * 还有就是存根数据的顺序很重要,但是它却很少有意义,例如 当使用完全相同的方法调用时,有时候使用参数匹配器等情况时。31 */32 /**33 * {@see Mockito34 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#235 * }36 */37 @Test38 public void step_2() {39 LinkedList mockedLinkList = mock(LinkedList.class);40 when(mockedLinkList.get(0)).thenReturn("first value");41 when(mockedLinkList.get(1)).thenThrow(new RuntimeException());42 //following prints "first"43 System.out.println(mockedLinkList.get(0));44 //following throws runtime exception45// System.out.println(mockedLinkList.get(1));46 //following prints "null" because get(999) was not stubbed47 System.out.println(mockedLinkList.get(999));48 //Although it is possible to verify a stubbed invocation, usually it's just redundant49 //If your code cares what get(0) returns, then something else breaks (often even before verify() gets executed).50 //If your code doesn't care what get(0) returns, then it should not be stubbed. Not convinced? See here.51 verify(mockedLinkList).get(0);52// verify(mockedLinkList).get(1);53 }54 /*55 * Mockito可以使用anyX()来替代任何的参数,但是如果需要自定义参数,那么就需要使用到 argument matchers56 * 使用ArgumentMatcher.argThat(matcher)方法,可以帮助我们校验相应的参数是否满足条件,从而验证有效性57 * 实际上所有的any方法,都是实现了相应的Matcher58 * 需要注意的是,如果你在调用相应的方法参数的时候使用了any方法,也就是说使用了Matcher,那么所有的方法都必须59 * 使用argument matchers60 * verify(mock).someMethod(anyInt(), anyString(), eq("third argument"));61 * //above is correct - eq() is also an argument matcher62 * verify(mock).someMethod(anyInt(), anyString(), "third argument");63 * //above is incorrect -64 * exception will be thrown because third argument is given without an argument matcher.65 */66 /**67 * {@see Mockito68 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#369 * }70 * {@see AdditionalMatchers71 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/AdditionalMatchers.html72 * }73 * [@see ArgumentMatchers74 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/ArgumentMatchers.html75 * }76 * {@see MockitoHamcrest77 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/hamcrest/MockitoHamcrest.html78 * }79 */80 @Test81 public void step_3() {82 LinkedList mockedList = mock(LinkedList.class);83 //stubbing using built-in anyInt() argument matcher84 when(mockedList.get(anyInt())).thenReturn("element");85 //stubbing using custom matcher (let's say isValid() returns your own matcher implementation):86 when(mockedList.contains(argThat(isValid()))).thenReturn(true);87 //following prints "element"88 System.out.println(mockedList.get(999));89 //you can also verify using an argument matcher90 verify(mockedList).get(anyInt());91 mockedList.add("element");92 //argument matchers can also be written as Java 8 Lambdas93// verify(mockedList).add(argThat(someString -> someString.length() > 5));94 verify(mockedList).add(argThat(new ArgumentMatcher<String>() {95 @Override96 public boolean matches(String argument) {97 return argument.length() > 5;98 }99 }));100 anyObject();101 }102 private ArgumentMatcher isValid() {103 return new ArgumentMatcher<String>() {104 @Override105 public boolean matches(String argument) {106 return argument.equals("element");107 }108 };109 }110 /*111 * 默认情况下,time(1)是默认被使用的,相应的方法是隐藏的,因此无需调用112 * 如果使用atLeast方法,可以校验至少执行了多少次113 * 如果使用atMost 方法,可以校验至多运行了多少次114 * never()代表,依次都没有运行115 */116 /**117 * {@see Verifying exact number of invocations / at least x / never118 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#4119 * }120 */121 @Test122 public void step_4() {123 LinkedList<Object> mockedList = mock(LinkedList.class);124 //using mock125 mockedList.add("once");126 mockedList.add("twice");127 mockedList.add("twice");128 mockedList.add("three times");129 mockedList.add("three times");130 mockedList.add("three times");131 //following two verifications work exactly the same - times(1) is used by default132 verify(mockedList).add("once");133 verify(mockedList, times(1)).add("once");134 //exact number of invocations verification135 verify(mockedList, times(2)).add("twice");136 verify(mockedList, times(3)).add("three times");137 //verification using never(). never() is an alias to times(0)138 verify(mockedList, never()).add("never happened");139 //verification using atLeast()/atMost()140 verify(mockedList, atLeastOnce()).add("three times");141 verify(mockedList, atLeast(2)).add("five times");142 verify(mockedList, atMost(5)).add("three times");143 }144 /*145 * 可以通过doThrow方法抛出相应的异常。146 * 下面的语句就表示 党执行mockedList执行clear()方法的时候,将抛出一个异常147 */148 /**149 * {@see Stubbing void methods with exceptions150 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#5151 * }152 */153 @Test154 public void step_5(){155 LinkedList mockedList = mock(LinkedList.class);156 doThrow(new RuntimeException()).when(mockedList).clear();157 //following throws RuntimeException:158 mockedList.clear();159 }160 /*161 * 使用inOrder可以帮助你来校验是否是顺序执行了需要测试的内容162 * 同时,你也可以通过InOrder对象,只传递与按顺序验证相关的mocks163 */164 /**165 * {@see Mockito166 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#6167 * }168 */169 @Test170 public void step_6() {171 // A. Single mock whose methods must be invoked in a particular order172 List<String> singleMock = mock(List.class);173 //using a single mock174 singleMock.add("was added first");175 singleMock.add("was added second");176 //create an inOrder verifier for a single mock177 InOrder inOrder = inOrder(singleMock);178 //following will make sure that add is first called with "was added first, then with "was added second"179 inOrder.verify(singleMock).add("was added first");180 inOrder.verify(singleMock).add("was added second");181 // B. Multiple mocks that must be used in a particular order182 List<String> firstMock = mock(List.class);183 List<String> secondMock = mock(List.class);184 //using mocks185 firstMock.add("was called first");186 secondMock.add("was called second");187 //create inOrder object passing any mocks that need to be verified in order188 InOrder anotherOrder = inOrder(secondMock,firstMock);189 //following will make sure that firstMock was called before secondMock190 anotherOrder.verify(firstMock).add("was called first");191 anotherOrder.verify(secondMock).add("was called second");192 // Oh, and A + B can be mixed together at will193 }194 /*195 * Making sure interaction(s) never happened on mock196 * 确认相互的测试不会产生影响197 */198 /**199 * {@see Mockito200 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#7201 * }202 */203 @Test204 public void step_7() {205 LinkedList<String> mockOne = mock(LinkedList.class);206 LinkedList<String> mockTwo = mock(LinkedList.class);207 LinkedList<String> mockThree = mock(LinkedList.class);208 //using mocks - only mockOne is interacted209 mockOne.add("one");210 //ordinary verification211 verify(mockOne).add("one");212 //verify that method was never called on a mock213 verify(mockOne, never()).add("two");214 //verify that other mocks were not interacted215 verifyZeroInteractions(mockTwo, mockThree);216 }217 /*218 * Finding redundant invocations219 * 通过使用verifyNoMoreInteractions确保相应的调用只执行一次220 * 同时不建议在每个测试方法中使用verifyNoMoreInteractions()。221 * 如果调用never()方法,则会更加明确的表明相应的意图222 */223 /**224 * {@see Mockito225 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#8226 * }227 */228 @Test229 public void step_8() {230 LinkedList<String> mockedList = mock(LinkedList.class);231 //using mocks232 mockedList.add("one");233 mockedList.add("two");234 verify(mockedList).add("one");235 verify(mockedList).add("two");236 //following verification will fail237 verifyNoMoreInteractions(mockedList);238 }239 /*240 * Shorthand for mocks creation - @Mock annotation241 * 使用@Mock可以帮助我们更加快速的创建相应的mock对象,同时拥有更好的可读性242 */243 /**244 * {@see Mockito245 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#9246 * }247 * {@see MockitoRule248 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/junit/MockitoRule.html249 * }250 * {@see MockitoAnnotations251 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/MockitoAnnotations.html252 * }253 */254 @Test255 public void step_9() {256// public class ArticleManagerTest {257//258// @Mock259// private ArticleCalculator calculator;260// @Mock261// private ArticleDatabase database;262// @Mock263// private UserProvider userProvider;264//265// private ArticleManager manager;266// }267// Important! This needs to be somewhere in the base class or a test runner:268//269// MockitoAnnotations.initMocks(testClass);270 }271 /*272 * Stubbing consecutive calls (iterator-style stubbing)273 * 给多次调用同样的方法,添加不同的返回值274 * 需要注意的是如果多次使用同样参数的方法,之后调用thenReturn,将会产生的效果是275 * 后一个会覆盖前一个的返回值。276 */277 /**278 * {@see Mockito279 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#10280 * }281 */282 @Test283 public void step_10() {284//285// when(mock.someMethod("some arg"))286// .thenThrow(new RuntimeException())287// .thenReturn("foo");288//289// //First call: throws runtime exception:290// mock.someMethod("some arg");291//292// //Second call: prints "foo"293// System.out.println(mock.someMethod("some arg"));...

Full Screen

Full Screen

Source:OfficalTest_Part_2.java Github

copy

Full Screen

1package com.joke.mock.offical_mock;2import org.junit.Assert;3import org.junit.Test;4import org.mockito.ArgumentCaptor;5import org.mockito.BDDMockito;6import org.mockito.Mockito;7import org.mockito.invocation.InvocationOnMock;8import org.mockito.stubbing.Answer;9import java.util.ArrayList;10import java.util.Arrays;11import java.util.LinkedList;12import java.util.List;13import static org.mockito.Mockito.CALLS_REAL_METHODS;14import static org.mockito.Mockito.anyInt;15import static org.mockito.Mockito.doAnswer;16import static org.mockito.Mockito.doReturn;17import static org.mockito.Mockito.mock;18import static org.mockito.Mockito.reset;19import static org.mockito.Mockito.spy;20import static org.mockito.Mockito.verify;21import static org.mockito.Mockito.when;22import static org.mockito.Mockito.withSettings;23public class OfficalTest_Part_2 {24 /*25 * Stubbing with callbacks26 * 可以使用Answer来进行修改相应的,比如在下面的例子中,我们修改相应的返回值,27 * 调用相应的add方法时,就会返回我们自定义的结果28 * 最好 thenReturn() or thenThrow()等方法,来进行相应的测试。29 */30 /**31 * {@see Mockito32 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#1133 * }34 */35 @Test36 public void step_11() {37 final LinkedList mockedLinkList = mock(LinkedList.class);38 when(mockedLinkList.remove(anyInt())).thenAnswer(new Answer<String>() {39 @Override40 public String answer(InvocationOnMock invocation) throws Throwable {41 Object[] arguments = invocation.getArguments();42 Object mock = invocation.getMock();43 return "called with arguments: " + Arrays.toString(arguments);44 }45 });46 System.out.println(mockedLinkList.remove(999));47 }48 /*49 * doReturn()|doThrow()| doAnswer()|doNothing()|doCallRealMethod() family of methods50 *51 */52 /**53 * {@see Mockito54 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#1255 * }56 */57 @Test58 public void step_12() {59 final LinkedList mockedLinkList = mock(LinkedList.class);60 when(mockedLinkList.get(0)).thenReturn(false);61 doAnswer(new Answer<Boolean>() {62 @Override63 public Boolean answer(InvocationOnMock invocation) throws Throwable {64 Object[] arguments = invocation.getArguments();65 Object mock = invocation.getMock();66 return mock == mockedLinkList;67 }68 }).when(mockedLinkList).get(anyInt());69 System.out.println(mockedLinkList.get(0));70 }71 /*72 * 当使用spy的时候,会真正调用相应的方法(除非使用其他手段修改相应的返回值, 比如doXxx())73 * 注意:应当尽可能仔细使用,并且尽量少地使用spy,比如在处理遗留的代码的时候74 * 在一个真正的对象上使用Spy,可以理解为“partial mocking”;但是在1.8之前,Mockito并不是真正75 * partial mock,原因在于,我们认为partial mock是代码的一部分。在某些方面,我们发现了使用部分mocks76 * 的合理之处(例如:第三方接口,遗留代码的临时重构,全部的文章,参考以下内容77 * {@see partial-mocking78 * https://monkeyisland.pl/2009/01/13/subclass-and-override-vs-partial-mocking-vs-refactoring/})79 * 有一点需要特别注意的是,在使用 when(Object)方法调用spy对象的时候,建议使用以下的方法替代doReturn|Answer|Throw()80 * 例如81 * //Impossible: real method is called so spy.get(0) throws IndexOutOfBoundsException (the list is yet empty)82 * when(spy.get(0)).thenReturn("ArrayList");83 * 由于spy并没有初始化,因此将会抛出相应的异常84 * //You have to use doReturn() for stubbing85 * doReturn("ArrayList").when(spy).get(0);86 *87 */88 /**89 * {@see Mockito90 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#1391 * }92 */93 @Test94 public void step_13() {95 List list = new LinkedList();96 List<String> spy = spy(list);97 //Impossible: real method is called so spy.get(0) throws IndexOutOfBoundsException (the list is yet empty)98 when(spy.get(0)).thenReturn("ArrayList");99 //You have to use doReturn() for stubbing100 doReturn("ArrayList").when(spy).get(0);101 //optionally, you can stub out some methods:102 when(spy.size()).thenReturn(100);103 //using the spy calls *real* methods104 spy.add("one");105 spy.add("two");106 //prints "one" - the first element of a list107 System.out.println(spy.get(0));108 //size() method was stubbed - 100 is printed109 System.out.println(spy.size());110 //optionally, you can verify111 verify(spy).add("one");112 verify(spy).add("two");113 }114 /*115 * Changing default return values of unstubbed invocations (Since 1.7)116 * 我们可以给相应的返回值,指定一个默认的规则。117 * 这是想当高级的功能,并且对于旧系统,来说是非常有帮助的118 * 默认情况下,你根本不需要调用它119 * 更多的内容,可以参考默认的实现。120 * {@see RETURNS_SMART_NULLS121 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#RETURNS_SMART_NULLS122 * }123 */124 /**125 * {@see Mockito126 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#14127 * }128 */129 @Test130 public void step_14() {131 List mock = mock(ArrayList.class, Mockito.RETURNS_SMART_NULLS);132 List mockTwo = mock(List.class, new Answer() {133 @Override134 public Object answer(InvocationOnMock invocation) throws Throwable {135 return false;136 }137 });138 System.out.println( mockTwo.add("haha"));139 }140 /*141 * Capturing arguments for further assertions (Since 1.8.0)142 * 这个功能,可以帮助你检验相应的参数的正确性143 * 警告:必须记住的是使用ArgumentCaptor 功能应该是检验而不是用来替代默认值。144 * 如果使用ArgumentCaptor 将减少代码的可读性,因为捕获是在assert之外创建,145 * (例如在aka verify 或者‘then’)146 * 它同时减少了定位缺陷,因为如果stubbed方法没有被调用,那么将不会有参数被捕获147 * ArgumentCaptor 更适用于以下情形:148 * 1、自定义argument matcher不太可能被重用149 * 2、你只需要验证函数参数的只就可以完成校验150 * {@see ArgumentMatcher151 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/ArgumentMatcher.html152 * }153 */154 /**155 * {@see Mockito156 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#15157 * }158 */159 @Test160 public void step_15() {161 ArrayList mock = mock(ArrayList.class);162 mock.add("John");163 ArgumentCaptor<List> argument = ArgumentCaptor.forClass(ArrayList.class);164 verify(mock).add(argument.capture());165 Assert.assertEquals("John", argument.getValue());166 }167 /*168 * Real partial mocks (Since 1.8.0)169 * 在部分情况下partial mocks是非常有用的170 * spy()与spy(Object)方法并没有产生正常的partial mocks,具体信息请阅读171 * {@see172 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#13173 * }174 * 需要注意的是:175 * 最好在测试第三方接口,以及遗留代码的时候使用spy176 * 不要在新设计的代码、可以测试的代码,以及良好设计的代码上使用spy177 *178 */179 /**180 * {@see Mockito181 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#16182 * }183 */184 @Test185 public void step_16() {186 //you can create partial mock with spy() method:187 List list = spy(new LinkedList());188 //you can enable partial mock capabilities selectively on mocks:189 ArrayList mock = mock(ArrayList.class);190 //Be sure the real implementation is 'safe'.191 //If real implementation throws exceptions or depends on specific state of the object then you're in trouble.192 when(mock.add("haha")).thenCallRealMethod();193 }194 /*195 * Resetting mocks (Since 1.8.0)196 * "Please keep us small & focused on single behavior".197 * 是我们应当遵循的规则,因此我们通常并不需要使用reset,除非在一个冗长的、超量的测试中使用。198 * 官方添加rest方法的唯一原因就是可以使用容器注入的模拟器。199 * {@see FAQ200 * https://github.com/mockito/mockito/wiki/FAQ201 * }202 * 告诉你自己:203 * 如果是使用reset方法,那么你可能写得太多了204 */205 /**206 * {@see Mockito207 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#17208 * }209 */210 @Test211 public void step_17() {212 List mock = mock(List.class);213 when(mock.size()).thenReturn(10);214 mock.add(1);215 reset(mock);216 //at this point the mock forgot any interactions & stubbing217 }218 /*219 * Troubleshooting & validating framework usage220 * {@see FAQ221 * https://github.com/mockito/mockito/wiki/FAQ222 * }223 * 或者可以参考224 * http://groups.google.com/group/mockito225 */226 /**227 * {@see Mockito228 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#18229 * }230 */231 @Test232 public void step_18() {233 }234 /*235 * Aliases for behavior driven development (Since 1.8.0)236 * Behavior Driven Development (基于行为驱动的开发)在执行测试时,可以使用237 * //given //when //then等方法作为你测试方法的一部分。238 * {@see Behavior Driven Development (BDD)239 * http://en.wikipedia.org/wiki/Behavior_Driven_Development240 * }241 * 问题是当前stubbing api与when字的规范作用,没有很好地集成//given//when//then注释。242 * 这是因为它属于given测试内容的stubbing,并不属于when测试内容的sutbbing243 * 因此,因此,BDDMockito类引入一个别名,244 * 以便使用BDDMockito.given(Object)方法进行stub方法调用。245 * 现在它真的很好地与BDD样式测试的给定组件集成!246 */247 /**248 * {@see Mockito249 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#19250 * }251 */252 @Test253 public void step_19() {254 ArrayList mock = mock(ArrayList.class);255 BDDMockito.given(mock.add("Test")).willReturn(false);256 System.out.println("mock.add(\"Test\") = " + mock.add("Test"));257 verify(mock).add("Test");258 }259 /*260 * Serializable mocks (Since 1.8.1)261 * Mocks可以被创作为可序列化对象。有了这个功能,你可以在一个需要依赖的地方使用一个模拟来进行序列化。262 * 警告:这个功能应该在单元测试中很少用到。263 * 对于具有不可靠的外部依赖性的BDD规范的特定用例,实施了该行为。264 * 这是在一个Web环境中,来自外部依赖关系的对象被序列化以在层之间传递。265 */266 /**267 * {@see Mockito268 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#269 * }270 */271 @Test272 public void step_20() {273 List serializableMock = mock(List.class, withSettings().serializable());274 //创建一个真正的对象spy serializable 是一个需要更多的努力,275 //因为spy(object)方法没有接受MockSettings的重载版本,别担心,几乎不会使用它。276 List<Object> list = new ArrayList<Object>();277 List<Object> spy = mock(ArrayList.class, withSettings()278 .spiedInstance(list)279 .defaultAnswer(CALLS_REAL_METHODS)280 .serializable());281 }282}...

Full Screen

Full Screen

Source:OfficalTest_Part_3.java Github

copy

Full Screen

1package com.joke.mock.offical_mock;2import org.junit.Test;3import org.mockito.InOrder;4import java.util.ArrayList;5import static org.mockito.Mockito.ignoreStubs;6import static org.mockito.Mockito.inOrder;7import static org.mockito.Mockito.mock;8import static org.mockito.Mockito.verify;9import static org.mockito.Mockito.verifyNoMoreInteractions;10import static org.mockito.Mockito.when;11public class OfficalTest_Part_3 {12 /*13 * New annotations: @Captor, @Spy, @InjectMocks (Since 1.8.3)14 * @Captor simplifies creation of ArgumentCaptor - useful when the argument to capture is a nasty generic class and you want to avoid compiler warnings15 * @Spy - you can use it instead spy(Object).16 * @InjectMocks - injects mock or spy fields into tested object automatically.17 * 需要注意的是InjectMocks可以与@Spy进行组合使用。这就意味着,Mockito将会注入mocks到 partial mock18 * 用以进行测试。虽然更加的复杂,但是却又一个很好的原因可以让你使用它,那就是它可以作为你使用partial mock19 * 的最后的手段。20 * 这些所有的注解,只在 MockitoAnnotations.initMocks(Object)中处理,就像你使用@Mock注解时,你可以使用21 * 内置的MockitoJUnitRunner or rule: MockitoRule.22 */23 /**24 * {@see Mockito25 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#2126 * }27 */28 @Test29 public void step_21() {30 }31 /*32 * Verification with timeout (Since 1.8.5)33 * 允许校验超时,它将会导致等待一个特殊的时间段,从而期望的事情发生,而不是立即发生。34 * 在测试并发的时候,它将可能很有用。35 * 它应该很少被使用到-在找到一个更好的测试多线程系统的方法。36 */37 /**38 * {@see Mockito39 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#2240 * }41 */42 @Test43 public void step_22() {44//45// //passes when someMethod() is called within given time span46// verify(mock, timeout(100)).someMethod();47// //above is an alias to:48// verify(mock, timeout(100).times(1)).someMethod();49//50// //passes when someMethod() is called *exactly* 2 times within given time span51// verify(mock, timeout(100).times(2)).someMethod();52//53// //passes when someMethod() is called *at least* 2 times within given time span54// verify(mock, timeout(100).atLeast(2)).someMethod();55//56// //verifies someMethod() within given time span using given verification mode57// //useful only if you have your own custom verification modes.58// verify(mock, new Timeout(100, yourOwnVerificationMode)).someMethod();59 }60 /*61 * Automatic instantiation of @Spies, @InjectMocks and constructor injection goodness (Since 1.9.0)62 * 我们通过组合@Spies,将会实例化、注入在使用@InjectMocks的构造函数、setter方法、或者全局变量上63 *64 * {@see65 * 了解相应的方法调用66 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/MockitoAnnotations.html#initMocks(java.lang.Object)67 * 了解JUnitRunner规则68 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/junit/MockitoJUnitRunner.html69 * 了解MockitoRule70 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/junit/MockitoRule.html71 * }72 * {@see InjectMocks 可以了解更多的注入的规则,以及限制73 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/InjectMocks.html74 * }75 */76 /**77 * {@see Mockito78 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#2379 * }80 */81 @Test82 public void step_23() {83 }84 /*85 * One-liner stubs (Since 1.9.0)86 * 我们可以可用一行代码来创建相应的mock对象保证简洁性,例如下面的例子87 * public class CarTest {88 * Car boringStubbedCar = when(mock(Car.class).shiftGear()).thenThrow(EngineNotStarted.class).getMock();89 * @Test public void should... {}90 * }91 */92 /**93 * {@see Mockito94 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#2495 * }96 */97 @Test98 public void step_24() {99 ArrayList test = when(mock(ArrayList.class).add("Test")).thenThrow(new RuntimeException()).getMock();100 test.add("haha"); //正常运行101 test.add("Test"); //抛出异常102 }103 /*104 * Verification ignoring stubs (Since 1.9.0)105 * verifyNoMoreInteractions() 或者verification inOrder() 可以帮助我们减少相应的冗余验证106 * 警告:107 * 需要注意的是ignoreStubs() 将会导致过度的使用verifyNoMoreInteractions(ignoreStubs(...))方法108 * 我们并不应该在每次test测试的时候都调用该verify方法,因为它只是在测试工具中作为一个简单的、方便的断言109 * 应当在那些需要使用该方法的时候再使用。110 * {@see111 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#verifyNoMoreInteractions(java.lang.Object...)112 * https://monkeyisland.pl/2008/07/12/should-i-worry-about-the-unexpected/113 * }114 */115 /**116 * {@see Mockito117 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#118 * }119 */120 @Test121 public void step_25() {122 ArrayList mock = mock(ArrayList.class);123 ArrayList mockTwo = mock(ArrayList.class);124 mock.clear();125 mockTwo.clear();126 verify(mock).clear();127 verify(mockTwo).clear();128 //ignores all stubbed methods:129 verifyNoMoreInteractions(ignoreStubs(mock, mockTwo));130 //creates InOrder that will ignore stubbed131 InOrder inOrder = inOrder(ignoreStubs(mock, mockTwo));132 inOrder.verify(mock).clear();133 inOrder.verify(mockTwo).clear();134 inOrder.verifyNoMoreInteractions();135 }136 /*137 * Mocking details (Improved in 2.2.x)138 * 可以帮助我们获取mock对象或者spy对象的一些具体的细节139 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/MockingDetails.html140 */141 /**142 * {@see Mockito143 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#26144 * }145 */146 @Test147 public void step_26() {148// //To identify whether a particular object is a mock or a spy:149// Mockito.mockingDetails(someObject).isMock();150// Mockito.mockingDetails(someObject).isSpy();151// //Getting details like type to mock or default answer:152// MockingDetails details = mockingDetails(mock);153// details.getMockCreationSettings().getTypeToMock();154// details.getMockCreationSettings().getDefaultAnswer();155// //Getting interactions and stubbings of the mock:156// MockingDetails details = mockingDetails(mock);157// details.getInteractions();158// details.getStubbings();159// //Printing all interactions (including stubbing, unused stubs)160// System.out.println(mockingDetails(mock).printInvocations());161 }162 /*163 * Delegate calls to real instance (Since 1.9.5)164 * 利用spies或者部分模拟的对象很难使用一般的spyApi来进行mock或者spy。而从1.10.11开始,这种委托的方法165 * 可能与mock相同,也可能与之不相同。如果类型不相同,那么在代表的类型中找到一个匹配的方法,否则将抛出异常166 * 以下是可能用到这种功能的情形:167 * Final classes but with an interface168 * Already custom proxied object169 * Special objects with a finalize method, i.e. to avoid executing it 2 times170 * 与通常的spy对象的不同之处在于171 * 1、通常的spy对象((spy(Object))从spied的实例中包含了所有的状态,并且这些方法都可以在spy对象上引用。172 * 这个spied的实例只是被当做,从已经创建的mock对象上复制所有的状态的一个对象。如果你在一个通常的spy对象173 * 上调用一些方法,并且它会在这个spy对象向调用其他方法。因此,这些调用将会被记录下来用于验证,并且他们可174 * 以有效的修改相应的存根数据(stubbed)175 * 2、mock对象代表着一个可以接收所有方法的简单委托的对象。这个委托可以在任何时候上调用它的所有方法。176 * 如果你在一个mock对象上调用一个方法,并且它内部在这个mock对象上调用了其他的方法,那么这些调用将不会177 * 记录下来用以验证,存根数据(stubbing)也没有对他们有任何影响。Mock相对于一个通常的spy对象来说,没有178 * 那么的强大,但是它可以非常有用的,在那些spy对象不能被创建的时候179 *180 */181 /**182 * {@see Mockito183 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#27184 * }185 */186 @Test187 public void step_27() {188 }189 /*190 * MockMaker API (Since 1.9.5)191 * 由于谷歌安卓上针对于设备以及补丁的需求,Mockito现在提供了一个扩展点,去替代代理生成引擎192 * 默认情况下,Mockito使用 byte-buddy来创建动态的代理193 * {byte-buddy194 * https://github.com/raphw/byte-buddy195 * }196 * 这个扩展点是针对于那些需要扩展Mockito的高级用户。现在可以利用dexMatcher来帮助进行一些197 * Android方面的Mockito测试198 * 更多的内容可以参考MockMarker199 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/plugins/MockMaker.html200 *201 */202 /**203 * {@see Mockito204 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#28205 * }206 */207 @Test208 public void step_28() {209 }210 /*211 * BDD style verification (Since 1.10.0)212 * Enables Behavior Driven Development (BDD) style verification by213 * starting verification with the BDD then keyword.214 * 可以参考以下的连接,获取更多的内容215 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/BDDMockito.html#then(T)216 */217 /**218 * {@see Mockito219 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#29220 * }221 */222 @Test223 public void step_29() {224 }225 /*226 * Spying or mocking abstract classes (Since 1.10.12, further enhanced in 2.7.13 and 2.7.14)227 * 在模拟抽象类的时候,这个功能非常的有用,因为它可以让你不再需要提供一个抽象类的实例228 * 目前只有较少参数的的改造方法的抽象类可以支持229 */230 /**231 * {@see Mockito232 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#30233 * }234 */235 @Test236 public void step_30() {237// //convenience API, new overloaded spy() method:238// SomeAbstract spy = spy(SomeAbstract.class);239//240// //Mocking abstract methods, spying default methods of an interface (only avilable since 2.7.13)241// Function function = spy(Function.class);242//243// //Robust API, via settings builder:244// OtherAbstract spy = mock(OtherAbstract.class, withSettings()245// .useConstructor().defaultAnswer(CALLS_REAL_METHODS));246//...

Full Screen

Full Screen

Source:OfficalTest_Part_4.java Github

copy

Full Screen

1package com.joke.mock.offical_mock;2import org.junit.Test;3import java.util.ArrayList;4import static org.mockito.Mockito.description;5import static org.mockito.Mockito.mock;6import static org.mockito.Mockito.times;7import static org.mockito.Mockito.verify;8public class OfficalTest_Part_4 {9 /*10 * Mockito mocks can be serialized / deserialized across classloaders (Since 1.10.0)11 * Mockito实现了从classloader中引入序列化。就好像任何对象来自于系列化之中,在mock层次中的所有12 * 类型都必须序列化,并且包含answers;13 * 还可以参考以下内容14 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/MockSettings.html#serializable(org.mockito.mock.SerializableMode)15 */16 /**17 * {@see Mockito18 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#3119 * }20 */21 @Test22 public void step_31() {23// // use regular serialization24// mock(Book.class, withSettings().serializable());25//26// // use serialization across classloaders27// mock(Book.class, withSettings().serializable(ACROSS_CLASSLOADERS));28 }29 /*30 * Better generic support with deep stubs (Since 1.10.0)31 * 在类中如果泛型信息被引入,这就意味着类可以这样被使用而没有mock行为。32 *33 * 注意:34 * 在大多数情况下,mock返回mock对象是错误的。35 */36 /**37 * {@see Mockito38 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#3239 * }40 */41 @Test42 public void step_32() {43//44// class Lines extends List<Line> {45// // ...46// }47//48// lines = mock(Lines.class, RETURNS_DEEP_STUBS);49//50// // Now Mockito understand this is not an Object but a Line51// Line line = lines.iterator().next();52 }53 /*54 * Mockito JUnit rule (Since 1.10.17)55 * 在初始化注解中比如@Mock @Spy @InjectMocks有两种手段与方法56 * 1、使用@RunWith(MockitoJUnitRunner.class)注解JUnit测试类57 * 2、在使用@Before注解的方法中使用MockitoAnnotations.initMocks(Object)58 * Mockito.rule()59 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/junit/MockitoJUnit.html#rule()60 */61 /**62 * {@see Mockito63 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#64 * }65 */66 @Test67 public void step_33() {68// @RunWith(YetAnotherRunner.class)69// public class TheTest {70// @Rule public MockitoRule mockito = MockitoJUnit.rule();71// // ...72// }73 }74 /*75 * Switch on or off plugins (Since 1.10.15)76 * 一个孵化功能使它在mockito的方式,将允许切换mockito插件。77 * PluginSwitch78 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/plugins/PluginSwitch.html79 */80 /**81 * {@see Mockito82 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#83 * }84 */85 @Test86 public void step_34() {87 }88 /*89 * Custom verification failure message (Since 2.1.0)90 * 如果校验失败的话,可以自定义的提示信息。91 */92 /**93 * {@see Mockito94 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#3595 * }96 */97 @Test98 public void step_35() {99 ArrayList mock = mock(ArrayList.class);100 // will print a custom message on verification failure101 verify(mock, description("This will print on failure")).clear();102 // will work with any verification mode103 verify(mock, times(2).description("someMethod should be called twice")).size();104 }105 /*106 * Java 8 Lambda Matcher Support (Since 2.1.0)107 *108 */109 /**110 * {@see Mockito111 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#36112 * }113 */114 @Test115 public void step_36() {116//117// // verify a list only had strings of a certain length added to it118// // note - this will only compile under Java 8119// verify(list, times(2)).add(argThat(string -> string.length() < 5));120//121// // Java 7 equivalent - not as neat122// verify(list, times(2)).add(argThat(new ArgumentMatcher(){123// public boolean matches(String arg) {124// return arg.length() < 5;125// }126// }));127//128// // more complex Java 8 example - where you can specify complex verification behaviour functionally129// verify(target, times(1)).receiveComplexObject(argThat(obj -> obj.getSubObject().get(0).equals("expected")));130//131// // this can also be used when defining the behaviour of a mock under different inputs132// // in this case if the input list was fewer than 3 items the mock returns null133// when(mock.someMethod(argThat(list -> list.size()<3))).willReturn(null);134 }135 /*136 *137 */138 /**139 * {@see Mockito140 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#37141 * }142 */143 @Test144 public void step_37() {145// // answer by returning 12 every time146// doAnswer(invocation -> 12).when(mock).doSomething();147//148// // answer by using one of the parameters - converting into the right149// // type as your go - in this case, returning the length of the second string parameter150// // as the answer. This gets long-winded quickly, with casting of parameters.151// doAnswer(invocation -> ((String)invocation.getArgument(1)).length())152// .when(mock).doSomething(anyString(), anyString(), anyString());153//154// // Example interface to be mocked has a function like:155// void execute(String operand, Callback callback);156//157// // the example callback has a function and the class under test158// // will depend on the callback being invoked159// void receive(String item);160//161// // Java 8 - style 1162// doAnswer(AdditionalAnswers.answerVoid((operand, callback) -> callback.receive("dummy"))163// .when(mock).execute(anyString(), any(Callback.class));164//165// // Java 8 - style 2 - assuming static import of AdditionalAnswers166// doAnswer(answerVoid((String operand, Callback callback) -> callback.receive("dummy"))167// .when(mock).execute(anyString(), any(Callback.class));168//169// // Java 8 - style 3 - where mocking function to is a static member of test class170// private static void dummyCallbackImpl(String operation, Callback callback) {171// callback.receive("dummy");172// }173//174// doAnswer(answerVoid(TestClass::dummyCallbackImpl)175// .when(mock).execute(anyString(), any(Callback.class));176//177// // Java 7178// doAnswer(answerVoid(new VoidAnswer2() {179// public void answer(String operation, Callback callback) {180// callback.receive("dummy");181// }})).when(mock).execute(anyString(), any(Callback.class));182//183// // returning a value is possible with the answer() function184// // and the non-void version of the functional interfaces185// // so if the mock interface had a method like186// boolean isSameString(String input1, String input2);187//188// // this could be mocked189// // Java 8190// doAnswer(AdditionalAnswers.answer((input1, input2) -> input1.equals(input2))))191// .when(mock).execute(anyString(), anyString());192//193// // Java 7194// doAnswer(answer(new Answer2() {195// public String answer(String input1, String input2) {196// return input1 + input2;197// }})).when(mock).execute(anyString(), anyString());198 }199 /*200 * Meta data and generic type retention (Since 2.1.0)201 * Mockito现在保留mocked方法以及类型上的注释信息,就像作为泛型属性数据一样。202 * 以前,模拟类型没有保留对类型的注释,除非它们被显式地继承,并且从未在方法上保留注释。203 * 因此,现在的条件如下:204 * 当时用Java8时,Mockito现在也会保留类型注解,这是默认行为,如果使用另一个MockMaker可能不会保留。205 */206 /**207 * {@see Mockito208 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#38209 * }210 */211 @Test212 public void step_38() {213// @MyAnnotation214// class Foo {215// List<String> bar() { ... }216// }217//218// Class<?> mockType = mock(Foo.class).getClass();219// assert mockType.isAnnotationPresent(MyAnnotation.class);220// assert mockType.getDeclaredMethod("bar").getGenericReturnType() instanceof ParameterizedType;221 }222 /*223 * Mocking final types, enums and final methods (Since 2.1.0)224 */225 /**226 * {@see Mockito227 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#39228 * }229 */230 @Test231 public void step_39() {232 }233 /*234 *235 */236 /**237 * {@see Mockito238 * https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html#239 * }240 */241 @Test242 public void step_40() {243 }244}...

Full Screen

Full Screen

Source:TabBrowserControlsConstraintsHelperTest.java Github

copy

Full Screen

...8import org.junit.Test;9import org.junit.runner.RunWith;10import org.mockito.ArgumentCaptor;11import org.mockito.Mock;12import org.mockito.Mockito;13import org.mockito.MockitoAnnotations;14import org.robolectric.annotation.Config;15import org.chromium.base.UserDataHost;16import org.chromium.base.test.BaseRobolectricTestRunner;17import org.chromium.base.test.util.JniMocker;18import org.chromium.chrome.browser.ChromeActivity;19import org.chromium.components.browser_ui.util.BrowserControlsVisibilityDelegate;20import org.chromium.content_public.browser.WebContents;21import org.chromium.content_public.common.BrowserControlsState;22import org.chromium.ui.base.WindowAndroid;23import java.lang.ref.WeakReference;24/** Unit tests for {@link TabBrowserControlsConstraintsHelper}. */25@RunWith(BaseRobolectricTestRunner.class)26@Config(manifest = Config.NONE)27public class TabBrowserControlsConstraintsHelperTest {28 private final UserDataHost mUserDataHost = new UserDataHost();29 @Rule30 public JniMocker mocker = new JniMocker();31 @Mock32 TabImpl mTab;33 @Mock34 WebContents mWebContents;35 @Mock36 TabDelegateFactory mDelegateFactory;37 @Mock38 TabBrowserControlsConstraintsHelper.Natives mJniMock;39 private TabBrowserControlsConstraintsHelper mHelper;40 private TabObserver mRegisteredTabObserver;41 private TestVisibilityDelegate mVisibilityDelegate;42 @Before43 public void setUp() {44 MockitoAnnotations.initMocks(this);45 mocker.mock(TabBrowserControlsConstraintsHelperJni.TEST_HOOKS, mJniMock);46 Mockito.when(mTab.getUserDataHost()).thenReturn(mUserDataHost);47 Mockito.when(mTab.getDelegateFactory()).thenReturn(mDelegateFactory);48 Mockito.when(mTab.getWebContents()).thenReturn(mWebContents);49 mVisibilityDelegate = new TestVisibilityDelegate();50 Mockito.when(mDelegateFactory.createBrowserControlsVisibilityDelegate(Mockito.any()))51 .thenReturn(mVisibilityDelegate);52 }53 private void initHelper() {54 ArgumentCaptor<TabObserver> observerArg = ArgumentCaptor.forClass(TabObserver.class);55 TabBrowserControlsConstraintsHelper.createForTab(mTab);56 mHelper = TabBrowserControlsConstraintsHelper.get(mTab);57 Mockito.verify(mTab).addObserver(observerArg.capture());58 mRegisteredTabObserver = observerArg.getValue();59 }60 @Test61 public void testUpdateVisibilityDelegate_onInitialized() {62 initHelper();63 Mockito.verify(mDelegateFactory, Mockito.never())64 .createBrowserControlsVisibilityDelegate(mTab);65 mRegisteredTabObserver.onInitialized(mTab, null, null, 0);66 Mockito.verify(mDelegateFactory, Mockito.times(1))67 .createBrowserControlsVisibilityDelegate(mTab);68 verifyUpdateState(BrowserControlsState.BOTH);69 mVisibilityDelegate.set(BrowserControlsState.SHOWN);70 verifyUpdateState(BrowserControlsState.SHOWN);71 }72 @Test73 public void testUpdateVisibilityDelegate_TabAlreadyInitializedAndAttached() {74 Mockito.when(mTab.isInitialized()).thenReturn(true);75 WindowAndroid window = Mockito.mock(WindowAndroid.class);76 Mockito.when(mWebContents.getTopLevelNativeWindow()).thenReturn(window);77 ChromeActivity activity = Mockito.mock(ChromeActivity.class);78 WeakReference<Context> activityRef = new WeakReference<>(activity);79 Mockito.when(window.getContext()).thenReturn(activityRef);80 initHelper();81 Mockito.verify(mDelegateFactory, Mockito.times(1))82 .createBrowserControlsVisibilityDelegate(mTab);83 verifyUpdateState(BrowserControlsState.BOTH);84 mVisibilityDelegate.set(BrowserControlsState.SHOWN);85 verifyUpdateState(BrowserControlsState.SHOWN);86 }87 @Test88 public void testUpdateVisibilityDelegate_onAttachmentChanged() {89 initHelper();90 Mockito.verify(mDelegateFactory, Mockito.never())91 .createBrowserControlsVisibilityDelegate(mTab);92 mRegisteredTabObserver.onActivityAttachmentChanged(mTab, null);93 Mockito.verify(mDelegateFactory, Mockito.never())94 .createBrowserControlsVisibilityDelegate(mTab);95 WindowAndroid window = Mockito.mock(WindowAndroid.class);96 mRegisteredTabObserver.onActivityAttachmentChanged(mTab, window);97 Mockito.verify(mDelegateFactory, Mockito.times(1))98 .createBrowserControlsVisibilityDelegate(mTab);99 verifyUpdateState(BrowserControlsState.BOTH);100 mVisibilityDelegate.set(BrowserControlsState.SHOWN);101 verifyUpdateState(BrowserControlsState.SHOWN);102 }103 @Test104 public void testUpdateVisibilityDelegate_ChangeDelegates() {105 initHelper();106 Mockito.verify(mDelegateFactory, Mockito.never())107 .createBrowserControlsVisibilityDelegate(mTab);108 mRegisteredTabObserver.onInitialized(mTab, null, null, 0);109 Mockito.verify(mDelegateFactory).createBrowserControlsVisibilityDelegate(mTab);110 Mockito.verifyNoMoreInteractions(mDelegateFactory);111 verifyUpdateState(BrowserControlsState.BOTH);112 mVisibilityDelegate.set(BrowserControlsState.HIDDEN);113 verifyUpdateState(BrowserControlsState.HIDDEN, false);114 TabDelegateFactory newDelegateFactory = Mockito.mock(TabDelegateFactory.class);115 TestVisibilityDelegate newVisibilityDelegate = new TestVisibilityDelegate();116 Mockito.when(mTab.getDelegateFactory()).thenReturn(newDelegateFactory);117 Mockito.when(newDelegateFactory.createBrowserControlsVisibilityDelegate(Mockito.any()))118 .thenReturn(newVisibilityDelegate);119 WindowAndroid window = Mockito.mock(WindowAndroid.class);120 mRegisteredTabObserver.onActivityAttachmentChanged(mTab, window);121 Mockito.verify(newDelegateFactory).createBrowserControlsVisibilityDelegate(mTab);122 verifyUpdateState(BrowserControlsState.BOTH);123 mVisibilityDelegate.set(BrowserControlsState.SHOWN);124 Mockito.verify(mJniMock, Mockito.never())125 .updateState(Mockito.anyLong(), Mockito.any(), Mockito.any(), Mockito.anyInt(),126 Mockito.anyInt(), Mockito.anyBoolean());127 }128 @Test129 public void testWebContentsSwap() {130 initHelper();131 Mockito.verify(mDelegateFactory, Mockito.never())132 .createBrowserControlsVisibilityDelegate(mTab);133 mRegisteredTabObserver.onInitialized(mTab, null, null, 0);134 Mockito.verify(mDelegateFactory).createBrowserControlsVisibilityDelegate(mTab);135 Mockito.verifyNoMoreInteractions(mDelegateFactory);136 verifyUpdateState(BrowserControlsState.BOTH);137 mRegisteredTabObserver.onWebContentsSwapped(mTab, true, true);138 verifyUpdateState(BrowserControlsState.BOTH);139 }140 @Test141 public void testWebContentsSwap_whenShown() {142 initHelper();143 Mockito.verify(mDelegateFactory, Mockito.never())144 .createBrowserControlsVisibilityDelegate(mTab);145 mRegisteredTabObserver.onInitialized(mTab, null, null, 0);146 Mockito.verify(mDelegateFactory).createBrowserControlsVisibilityDelegate(mTab);147 Mockito.verifyNoMoreInteractions(mDelegateFactory);148 verifyUpdateState(BrowserControlsState.BOTH);149 mVisibilityDelegate.set(BrowserControlsState.SHOWN);150 verifyUpdateState(BrowserControlsState.SHOWN);151 mRegisteredTabObserver.onWebContentsSwapped(mTab, true, true);152 verifyUpdateState(BrowserControlsState.SHOWN, BrowserControlsState.SHOWN, false);153 }154 private void verifyUpdateState(@BrowserControlsState int constraints) {155 verifyUpdateState(constraints, BrowserControlsState.BOTH, true);156 }157 private void verifyUpdateState(@BrowserControlsState int constraints, boolean animate) {158 verifyUpdateState(constraints, BrowserControlsState.BOTH, animate);159 }160 private void verifyUpdateState(@BrowserControlsState int constraints,161 @BrowserControlsState int current, boolean animate) {162 Mockito.verify(mJniMock).updateState(Mockito.anyLong(), Mockito.same(mHelper),163 Mockito.same(mWebContents), Mockito.eq(constraints), Mockito.eq(current),164 Mockito.eq(animate));165 Mockito.clearInvocations(mJniMock);166 }167 private static class TestVisibilityDelegate extends BrowserControlsVisibilityDelegate {168 public TestVisibilityDelegate() {169 super(BrowserControlsState.BOTH);170 }171 }172}...

Full Screen

Full Screen

Source:PartnerBookmarksReaderTest.java Github

copy

Full Screen

...9import org.junit.runner.RunWith;10import org.mockito.ArgumentCaptor;11import org.mockito.Captor;12import org.mockito.Mock;13import org.mockito.Mockito;14import org.mockito.MockitoAnnotations;15import org.robolectric.annotation.Config;16import org.chromium.base.test.BaseRobolectricTestRunner;17import org.chromium.base.test.util.JniMocker;18import org.chromium.chrome.browser.partnercustomizations.PartnerBrowserCustomizations;19/**20 * Unit tests for PartnerBookmarksReader.21 */22@RunWith(BaseRobolectricTestRunner.class)23@Config(manifest = Config.NONE)24public class PartnerBookmarksReaderTest {25 @Rule26 public JniMocker mocker = new JniMocker();27 @Mock28 Context mContextMock;29 @Mock30 PartnerBookmarksReader.Natives mJniMock;31 @Mock32 PartnerBrowserCustomizations mBrowserCustomizations;33 @Captor34 ArgumentCaptor<Runnable> mBrowserCustomizationsInitCallback;35 @Before36 public void setUp() {37 MockitoAnnotations.initMocks(this);38 mocker.mock(PartnerBookmarksReaderJni.TEST_HOOKS, mJniMock);39 Mockito.doNothing()40 .when(mBrowserCustomizations)41 .setOnInitializeAsyncFinished(mBrowserCustomizationsInitCallback.capture());42 }43 @Test44 public void partnerBrowserCustomizations_BookmarkEditingDisabled_AlreadyInitialized() {45 Mockito.when(mBrowserCustomizations.isInitialized()).thenReturn(true);46 @SuppressWarnings("unused")47 PartnerBookmarksReader reader =48 new PartnerBookmarksReader(mContextMock, mBrowserCustomizations);49 Mockito.verify(mBrowserCustomizations, Mockito.never()).initializeAsync(mContextMock);50 Mockito.when(mBrowserCustomizations.isBookmarksEditingDisabled()).thenReturn(true);51 mBrowserCustomizationsInitCallback.getValue().run();52 Mockito.verify(mJniMock).disablePartnerBookmarksEditing();53 }54 @Test55 public void partnerBrowserCustomizations_BookmarkEditingDisabled_NotAlreadyInitialized() {56 Mockito.when(mBrowserCustomizations.isInitialized()).thenReturn(false);57 @SuppressWarnings("unused")58 PartnerBookmarksReader reader =59 new PartnerBookmarksReader(mContextMock, mBrowserCustomizations);60 Mockito.verify(mBrowserCustomizations).initializeAsync(mContextMock);61 Mockito.when(mBrowserCustomizations.isBookmarksEditingDisabled()).thenReturn(true);62 mBrowserCustomizationsInitCallback.getValue().run();63 Mockito.verify(mJniMock).disablePartnerBookmarksEditing();64 }65 @Test66 public void partnerBrowserCustomizations_BookmarkEditingAllowed_AlreadyInitialized() {67 Mockito.when(mBrowserCustomizations.isInitialized()).thenReturn(true);68 @SuppressWarnings("unused")69 PartnerBookmarksReader reader =70 new PartnerBookmarksReader(mContextMock, mBrowserCustomizations);71 Mockito.verify(mBrowserCustomizations, Mockito.never()).initializeAsync(mContextMock);72 Mockito.when(mBrowserCustomizations.isBookmarksEditingDisabled()).thenReturn(false);73 mBrowserCustomizationsInitCallback.getValue().run();74 Mockito.verify(mJniMock, Mockito.never()).disablePartnerBookmarksEditing();75 }76 @Test77 public void partnerBrowserCustomizations_BookmarkEditingAllowed_NotAlreadyInitialized() {78 Mockito.when(mBrowserCustomizations.isInitialized()).thenReturn(false);79 @SuppressWarnings("unused")80 PartnerBookmarksReader reader =81 new PartnerBookmarksReader(mContextMock, mBrowserCustomizations);82 Mockito.verify(mBrowserCustomizations).initializeAsync(mContextMock);83 Mockito.when(mBrowserCustomizations.isBookmarksEditingDisabled()).thenReturn(false);84 mBrowserCustomizationsInitCallback.getValue().run();85 Mockito.verify(mJniMock, Mockito.never()).disablePartnerBookmarksEditing();86 }87 @Test88 public void partnerBookmarksCreationComplete_NotCalledWithoutBrowserCustomizations() {89 Mockito.when(mBrowserCustomizations.isInitialized()).thenReturn(true);90 @SuppressWarnings("unused")91 PartnerBookmarksReader reader =92 new PartnerBookmarksReader(mContextMock, mBrowserCustomizations);93 reader.onBookmarksRead();94 Mockito.verify(mJniMock, Mockito.never())95 .partnerBookmarksCreationComplete(Mockito.anyLong(), Mockito.any());96 }97 @Test98 public void partnerBookmarksCreationComplete_NotCalledWithoutBookmarksRead() {99 Mockito.when(mBrowserCustomizations.isInitialized()).thenReturn(true);100 @SuppressWarnings("unused")101 PartnerBookmarksReader reader =102 new PartnerBookmarksReader(mContextMock, mBrowserCustomizations);103 Mockito.when(mBrowserCustomizations.isBookmarksEditingDisabled()).thenReturn(false);104 mBrowserCustomizationsInitCallback.getValue().run();105 Mockito.verify(mJniMock, Mockito.never())106 .partnerBookmarksCreationComplete(Mockito.anyLong(), Mockito.any());107 }108 @Test109 public void partnerBookmarksCreationComplete_Called_WithCustomizationsFirstThenBookmarks() {110 Mockito.when(mBrowserCustomizations.isInitialized()).thenReturn(true);111 @SuppressWarnings("unused")112 PartnerBookmarksReader reader =113 new PartnerBookmarksReader(mContextMock, mBrowserCustomizations);114 Mockito.when(mBrowserCustomizations.isBookmarksEditingDisabled()).thenReturn(false);115 mBrowserCustomizationsInitCallback.getValue().run();116 reader.onBookmarksRead();117 Mockito.verify(mJniMock).partnerBookmarksCreationComplete(118 Mockito.anyLong(), Mockito.eq(reader));119 }120 @Test121 public void partnerBookmarksCreationComplete_Called_WithBookmarksFirstThenCustomizations() {122 Mockito.when(mBrowserCustomizations.isInitialized()).thenReturn(true);123 @SuppressWarnings("unused")124 PartnerBookmarksReader reader =125 new PartnerBookmarksReader(mContextMock, mBrowserCustomizations);126 Mockito.when(mBrowserCustomizations.isBookmarksEditingDisabled()).thenReturn(false);127 reader.onBookmarksRead();128 mBrowserCustomizationsInitCallback.getValue().run();129 Mockito.verify(mJniMock).partnerBookmarksCreationComplete(130 Mockito.anyLong(), Mockito.eq(reader));131 }132}...

Full Screen

Full Screen

Source:RedisSingleTest.java Github

copy

Full Screen

...4import org.junit.Before;5import org.junit.Test;6import org.mockito.InjectMocks;7import org.mockito.Mock;8import org.mockito.Mockito;9import org.mockito.MockitoAnnotations;10import org.springframework.data.redis.connection.RedisClusterConnection;11import org.springframework.data.redis.connection.RedisConnection;12import org.springframework.data.redis.connection.jedis.JedisClusterConnection;13import org.springframework.data.redis.connection.jedis.JedisConnection;14import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;15import redis.clients.jedis.Jedis;16import redis.clients.jedis.JedisCluster;17import java.util.UUID;18/**19 * Function:20 *21 * @author crossoverJie22 * Date: 28/03/2018 23:3523 * @since JDK 1.824 */25public class RedisSingleTest {26 private RedisLock redisLock;27 @Mock28 private JedisConnectionFactory jedisConnectionFactory ;29 @Mock30 private Jedis jedis;31 @Before32 public void setBefore() {33 MockitoAnnotations.initMocks(this);34 redisLock = new RedisLock.Builder(jedisConnectionFactory, RedisToolsConstant.SINGLE)35 .lockPrefix("lock_")36 .sleepTime(100)37 .build();38 RedisConnection redisConnection = new JedisConnection(jedis) ;39 Mockito.when(jedisConnectionFactory.getConnection()).thenReturn(redisConnection);40 jedis = (Jedis)redisConnection.getNativeConnection();41 }42 @Test43 public void unlock() throws Exception {44 Mockito.when(jedis.eval(Mockito.anyString(), Mockito.anyList(), Mockito.anyList())).thenReturn(1L) ;45 boolean locktest = redisLock.unlock("test", "ec8ebca0-14ba0-4b23-99a8-b35fbba3629e");46 Assert.assertTrue(locktest);47 Mockito.verify(jedis).eval(Mockito.anyString(), Mockito.anyList(), Mockito.anyList());48 }49 @Test50 public void tryLock() throws Exception {51 String key = "test";52 String request = UUID.randomUUID().toString();53 Mockito.when(jedis.set(Mockito.anyString(), Mockito.anyString(),54 Mockito.anyString(), Mockito.anyString(), Mockito.anyInt()))55 .thenReturn("OK");56 boolean locktest = redisLock.tryLock(key, request);57 System.out.println("locktest=" + locktest);58 Assert.assertTrue(locktest);59 //check60 Mockito.verify(jedis).set(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(),61 Mockito.anyString(), Mockito.anyInt());62 }63 @Test64 public void lock() throws Exception {65 Mockito.when(jedis.set(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(),66 Mockito.anyString(), Mockito.anyInt())).thenReturn("OK");67 long start = System.currentTimeMillis();68 redisLock.lock("test", UUID.randomUUID().toString());69 long end = System.currentTimeMillis();70 System.out.println("lock success expire=" + (end - start));71 Mockito.verify(jedis).set(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(),72 Mockito.anyString(), Mockito.anyInt());73 }74 @Test75 public void lock2() throws Exception {76 Mockito.when(jedis.set(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(),77 Mockito.anyString(), Mockito.anyInt())).thenReturn("OK");78 long start = System.currentTimeMillis();79 boolean lock = redisLock.lock("test", UUID.randomUUID().toString(), 100);80 long end = System.currentTimeMillis();81 System.out.println("lock success expire=" + (end - start) + " lock = " + lock);82 Assert.assertTrue(lock);83 Mockito.verify(jedis).set(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(),84 Mockito.anyString(), Mockito.anyInt());85 }86 @Test87 public void lock2False() throws Exception {88 Mockito.when(jedis.set(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(),89 Mockito.anyString(), Mockito.anyInt())).thenReturn(null);90 long start = System.currentTimeMillis();91 boolean lock = redisLock.lock("test", UUID.randomUUID().toString(), 100);92 long end = System.currentTimeMillis();93 System.out.println("lock success expire=" + (end - start) + " lock = " + lock);94 Assert.assertFalse(lock);95 //check was called 2 times96 Mockito.verify(jedis,Mockito.times(2)).set(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(),97 Mockito.anyString(), Mockito.anyInt());98 }99 @Test100 public void tryLock2() throws Exception {101 Mockito.when(jedis.set(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(),102 Mockito.anyString(), Mockito.anyInt())).thenReturn("OK");103 boolean lock = redisLock.tryLock("test", UUID.randomUUID().toString(), 10 * 1000);104 Assert.assertTrue(lock);105 Mockito.verify(jedis).set(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(),106 Mockito.anyString(), Mockito.anyInt());107 }108 @Test109 public void tryLock2False() throws Exception {110 Mockito.when(jedis.set(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(),111 Mockito.anyString(), Mockito.anyInt())).thenReturn(null);112 boolean lock = redisLock.tryLock("test", UUID.randomUUID().toString(), 10 * 1000);113 Assert.assertFalse(lock);114 Mockito.verify(jedis).set(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(),115 Mockito.anyString(), Mockito.anyInt());116 }117}...

Full Screen

Full Screen

Source:ProjectPersistenceTest.java Github

copy

Full Screen

...7import org.hibernate.SessionFactory;8import org.hibernate.criterion.Criterion;9import org.junit.Before;10import org.junit.Test;11import org.mockito.Mockito;12import com.globallogic.dogo.domain.Project;13import com.globallogic.dogo.mo.ProjectMO;14import com.globallogic.dogo.persistence.exception.ObjectNotFoundException;15public class ProjectPersistenceTest {16 17 private ProjectPersistence persistence;18 private SessionFactory mockedSessionFactory;19 private Session mockedSession;20 21 @Before22 public void setUp(){23 this.mockedSessionFactory = Mockito.mock(SessionFactory.class);24 this.mockedSession = Mockito.mock(Session.class);25 Mockito.when(mockedSessionFactory.openSession()).thenReturn(mockedSession);26 this.persistence = new ProjectPersistence(mockedSessionFactory);27 }28 29 @Test30 public void testList(){31 List<Project> mockedResult = new ArrayList<Project>();32 Criteria mockedCriteria = Mockito.mock(Criteria.class);33 Mockito.when(mockedSession.createCriteria(Project.class)).thenReturn(mockedCriteria);34 Mockito.when(mockedCriteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY)).thenReturn(mockedCriteria);35 Mockito.when(mockedCriteria.list()).thenReturn(mockedResult);36 List<Project> result = this.persistence.list();37 Assert.assertNotNull(result);38 Assert.assertEquals(mockedResult, result);39 Mockito.verify(mockedSession,Mockito.times(1)).createCriteria(Project.class);40 Mockito.verify(mockedCriteria,Mockito.times(1)).setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);41 Mockito.verify(mockedCriteria,Mockito.times(1)).list();42 Mockito.verify(mockedSession,Mockito.times(1)).close();43 }44 45 @Test46 public void testGet() throws ObjectNotFoundException{47 Project mockedResult = ProjectMO.build();48 Criteria mockedCriteria = Mockito.mock(Criteria.class);49 Mockito.when(mockedSession.createCriteria(Project.class)).thenReturn(mockedCriteria);50 Mockito.when(mockedCriteria.add(Mockito.any(Criterion.class))).thenReturn(mockedCriteria);51 Mockito.when(mockedCriteria.uniqueResult()).thenReturn(mockedResult);52 Project result = this.persistence.findById(ProjectMO.ID);53 Assert.assertNotNull(result);54 Assert.assertEquals(mockedResult, result);55 Mockito.verify(mockedSession,Mockito.times(1)).createCriteria(Project.class);56 Mockito.verify(mockedCriteria,Mockito.times(1)).add(Mockito.any(Criterion.class));57 Mockito.verify(mockedCriteria,Mockito.times(1)).uniqueResult();58 Mockito.verify(mockedSession,Mockito.times(1)).close();59 }60 61 @Test(expected = ObjectNotFoundException.class)62 public void testGetNull() throws ObjectNotFoundException{63 Criteria mockedCriteria = Mockito.mock(Criteria.class);64 Mockito.when(mockedSession.createCriteria(Project.class)).thenReturn(mockedCriteria);65 Mockito.when(mockedCriteria.add(Mockito.any(Criterion.class))).thenReturn(mockedCriteria);66 Mockito.when(mockedCriteria.uniqueResult()).thenReturn(null);67 Project result = this.persistence.findById(ProjectMO.ID);68 Assert.assertNull(result);69 Mockito.verify(mockedSession,Mockito.times(1)).createCriteria(Project.class);70 Mockito.verify(mockedCriteria,Mockito.times(1)).add(Mockito.any(Criterion.class));71 Mockito.verify(mockedCriteria,Mockito.times(1)).uniqueResult();72 Mockito.verify(mockedSession,Mockito.times(1)).close();73 }74 75 @Test76 public void testSave(){77 Project mockedProject = ProjectMO.build();78 this.persistence.create(mockedProject);79 Mockito.verify(mockedSession, Mockito.times(1)).save(mockedProject);80 Mockito.verify(mockedSession, Mockito.times(1)).flush();81 Mockito.verify(mockedSession, Mockito.times(1)).close();82 }83}...

Full Screen

Full Screen

Mockito

Using AI Code Generation

copy

Full Screen

1import org.mockito.Mockito;2import org.mockito.Mock;3import org.mockito.MockitoAnnotations;4import org.mockito.InjectMocks;5import org.mockito.runners.MockitoJUnitRunner;6import org.junit.runner.RunWith;7import org.junit.Before;8import org.junit.Test;9import static org.junit.Assert.*;10import static org.mockito.Mockito.*;11@RunWith(MockitoJUnitRunner.class)12public class Test1 {13private List mockedList;14public void setup() {15MockitoAnnotations.initMocks(this);16}17public void test() {18mockedList.add("one");19verify(mockedList).add("one");20}21}22import static org.mockito.Mockito.*;23import org.mockito.Mock;24import org.mockito.MockitoAnnotations;25import org.mockito.InjectMocks;26import org.mockito.runners.MockitoJUnitRunner;27import org.junit.runner.RunWith;28import org.junit.Before;29import org.junit.Test;30import static org.junit.Assert.*;31import java.util.List;32@RunWith(MockitoJUnitRunner.class)33public class Test1 {34private List mockedList;35public void setup() {36MockitoAnnotations.initMocks(this);37}38public void test() {39mockedList.add("one");40verify(mockedList).add("one");41}42}

Full Screen

Full Screen

Mockito

Using AI Code Generation

copy

Full Screen

1import org.mockito.Mockito;2import org.mockito.ArgumentCaptor;3import org.mockito.invocation.InvocationOnMock;4import org.mockito.stubbing.Answer;5import java.util.List;6public class 1 {7 public static void main(String[] args) {8 List mockedList = Mockito.mock(List.class);9 mockedList.add("one");10 mockedList.clear();11 Mockito.verify(mockedList).add("one");12 Mockito.verify(mockedList).clear();13 }14}15import org.mockito.Mockito;16import org.mockito.ArgumentCaptor;17import org.mockito.invocation.InvocationOnMock;18import org.mockito.stubbing.Answer;19import java.util.List;20public class 2 {21 public static void main(String[] args) {22 LinkedList mockedList = Mockito.mock(LinkedList.class);23 Mockito.when(mockedList.get(0)).thenReturn("first");24 System.out.println(mockedList.get(0));25 System.out.println(mockedList.get(999));26 }27}28import org.mockito.Mockito;29import org.mockito.ArgumentCaptor;30import org.mockito.invocation.InvocationOnMock;31import org.mockito.stubbing.Answer;32import java.util.List;33public class 3 {34 public static void main(String[] args) {35 LinkedList mockedList = Mockito.mock(LinkedList.class);36 Mockito.when(mockedList.get(Mockito.anyInt())).thenReturn("element");37 Mockito.when(mockedList.contains(Mockito.argThat(isValid()))).thenReturn("element");38 System.out.println(mockedList.get(999));39 Mockito.verify(mockedList).get(Mockito.anyInt());40 Mockito.verify(mock

Full Screen

Full Screen

Mockito

Using AI Code Generation

copy

Full Screen

1import org.mockito.Mockito;2import org.mockito.Mockito.*;3import org.mockito.Matchers.*;4import static org.mockito.Mockito.*;5import static org.mockito.Matchers.*;6import org.mockito.ArgumentCaptor;7import org.mockito.Captor;8import org.mockito.Mock;9import org.mockito.MockitoAnnotations;10import org.mockito.runners.MockitoJUnitRunner;11import org.mockito.stubbing.OngoingStubbing;12import org.mockito.stubbing.Stubber;13import org.mockito.invocation.InvocationOnMock;14import org.mockito.stubbing.Answer;15import org.mockito.verification.VerificationMode;16import org.mockito.exceptions.base.MockitoAssertionError;17import org.mockito.exceptions.verification.NeverWantedButInvoked;18import org.mockito.exceptions.verification.WantedButNotInvoked;19import org.mockito.exceptions.verification.NoInteractionsWanted;20import org.mockito.exceptions.verification.TooLittleActualInvocations;21import org.mockito.exceptions.verification.TooManyActualInvocations;22import org.mockito.exceptions.verification.VerificationInOrderFailure;23import org.mockito.exceptions.verification.VerificationAsse

Full Screen

Full Screen

Mockito

Using AI Code Generation

copy

Full Screen

1import java.util.List;2import static org.mockito.Mockito.mock;3import static org.mockito.Mockito.when;4import static org.mockito.Mockito.verify;5import static org.mockito.Mockito.times;6import static org.mockito.Mockito.doNothing;7import static org.mockito.Mockito.doThrow;8import static org.mockito.Mockito.doReturn;9import static org.mockito.Mockito.spy;10import static org.mockito.Mockito.doCallRealMethod;11import static org.mockito.Mockito.doAnswer;12import static org.mockito.Mockito.doNothing;13import static org.mockito.Mockito.inOrder;14import static org.mockito.Mockito.atLeastOnce;15import static org.mockito.Mockito.atLeast;16import static org.mockito.Mockito.atMost;17import static org.mockito.Mockito.never;18import static org.mockito.Mockito.only;19import static org.mockito.Mockito.timeout;20import static org.mockito.Mockito.verifyNoMoreInteractions;21import static org.mockito.Mockito.verifyZeroInteractions;22import static org.m

Full Screen

Full Screen

Mockito

Using AI Code Generation

copy

Full Screen

1import org.mockito.Mockito;2import org.mockito.invocation.InvocationOnMock;3import org.mockito.stubbing.Answer;4public class MockitoExample {5 public static void main(String[] args) {6 TestClass mockObj = Mockito.mock(TestClass.class);7 Answer<Integer> answer = new Answer<Integer>() {8 public Integer answer(InvocationOnMock invocation) {9 Object[] args = invocation.getArguments();10 Integer arg1 = (Integer) args[0];11 Integer arg2 = (Integer) args[1];12 return arg1 + arg2;13 }14 };15 Mockito.when(mockObj.add(5, 10)).thenAnswer(answer);16 System.out.println(mockObj.add(5, 10));17 }18}19Mockito verify() Method Example20Mockito doReturn() Method Example21Mockito doThrow() Method Example22Mockito doCallRealMethod() Method Example23Mockito doNothing() Method Example24Mockito doAnswer() Method Example25Mockito spy() Method Example26Mockito mock() Method Example27Mockito reset() Method Example28Mockito timeout() Method Example29Mockito verifyNoMoreInteractions() Method Example30Mockito verifyNoInteractions() Method Example31Mockito verifyZeroInteractions() Method Example32Mockito verifyNoMoreInteractions() Method Example33Mockito verify() Method Example34Mockito verify() Method Example35Mockito times() Method Example36Mockito atLeastOnce() Method Example37Mockito atLeast() Method Example38Mockito atMost() Method Example39Mockito never() Method Example40Mockito only() Method Example41Mockito doThrow() Method Example42Mockito doReturn() Method Example43Mockito doNothing() Method Example44Mockito doCallRealMethod() Method Example45Mockito doAnswer() Method Example

Full Screen

Full Screen

Mockito

Using AI Code Generation

copy

Full Screen

1import org.mockito.Mockito;2import static org.mockito.Mockito.*;3public class MyClass {4 public int myMethod(int a, int b) {5 return a + b;6 }7}8public class TestClass {9 public void testMethod() {10 MyClass test = Mockito.mock(MyClass.class);11 when(test.myMethod(1, 2)).thenReturn(3);12 assertEquals(3, test.myMethod(1, 2));13 }14}15import org.mockito.Mockito;16import static org.mockito.Mockito.*;17public class MyClass {18 public int myMethod(int a, int b) {19 return a + b;20 }21}22public class TestClass {23 public void testMethod() {24 MyClass test = Mockito.mock(MyClass.class);25 when(test.myMethod(1, 2)).thenReturn(3);26 assertEquals(3, test.myMethod(1, 2));27 }28}29import org.mockito.Mockito;30import static org.mockito.Mockito.*;31public class MyClass {32 public int myMethod(int a, int b) {33 return a + b;34 }35}36public class TestClass {37 public void testMethod() {38 MyClass test = Mockito.mock(MyClass.class);39 when(test.myMethod(1, 2)).thenReturn(3);40 assertEquals(3, test.myMethod(1, 2));41 }42}43import org.mockito.Mockito;44import static org.mockito.Mockito.*;45public class MyClass {46 public int myMethod(int a, int b) {47 return a + b;48 }49}50public class TestClass {51 public void testMethod() {52 MyClass test = Mockito.mock(MyClass.class);53 when(test.myMethod(1, 2)).thenReturn(3);54 assertEquals(3, test.myMethod(1, 2));55 }56}57import org.mockito.Mockito;58import static org.mockito.Mockito.*;

Full Screen

Full Screen

Mockito

Using AI Code Generation

copy

Full Screen

1import org.mockito.Mockito;2public class Test1 {3public static void main(String[] args) {4 Test t = Mockito.mock(Test.class);5 Mockito.when(t.add(10, 20)).thenReturn(30);6 Mockito.when(t.add(20, 20)).thenReturn(40);7 System.out.println(t.add(10, 20));8 System.out.println(t.add(20, 20));9}10}

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