How to use mock method of org.mockito.Mockito class

Best Mockito code snippet using org.mockito.Mockito.mock

Source:OfficalTest_Part_1.java Github

copy

Full Screen

1package com.joke.mock.offical_mock;2import org.junit.Test;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"));294//295// //Any consecutive call: prints "foo" as well (last stubbing wins).296// System.out.println(mock.someMethod("some arg"));297//298// Alternative, shorter version of consecutive stubbing:299//300// when(mock.someMethod("some arg"))301// .thenReturn("one", "two", "three");302//303// Warning : if instead of chaining .thenReturn() calls, multiple stubbing with the same matchers or arguments is used, then each stubbing will override the previous one:304//305// //TODO:All mock.someMethod("some arg") calls will return "two"306// when(mock.someMethod("some arg"))307// .thenReturn("one")308// when(mock.someMethod("some arg"))309// .thenReturn("two")310 }311}...

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//247// //Mocking an abstract class with constructor arguments (only available since 2.7.14)248// SomeAbstract spy = mock(SomeAbstract.class, withSettings()249// .useConstructor("arg1", 123).defaultAnswer(CALLS_REAL_METHODS));250//251// //Mocking a non-static inner abstract class:252// InnerAbstract spy = mock(InnerAbstract.class, withSettings()253// .useConstructor().outerInstance(outerInstance).defaultAnswer(CALLS_REAL_METHODS));254 }255}...

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:TestCachingKeyProvider.java Github

copy

Full Screen

...20import org.apache.hadoop.conf.Configuration;21import org.apache.hadoop.crypto.key.kms.KMSClientProvider;22import org.junit.Assert;23import org.junit.Test;24import org.mockito.Mockito;25public class TestCachingKeyProvider {26 @Test27 public void testCurrentKey() throws Exception {28 KeyProvider.KeyVersion mockKey = Mockito.mock(KeyProvider.KeyVersion.class);29 KeyProvider mockProv = Mockito.mock(KeyProvider.class);30 Mockito.when(mockProv.getCurrentKey(Mockito.eq("k1"))).thenReturn(mockKey);31 Mockito.when(mockProv.getCurrentKey(Mockito.eq("k2"))).thenReturn(null);32 Mockito.when(mockProv.getConf()).thenReturn(new Configuration());33 KeyProvider cache = new CachingKeyProvider(mockProv, 100, 100);34 // asserting caching35 Assert.assertEquals(mockKey, cache.getCurrentKey("k1"));36 Mockito.verify(mockProv, Mockito.times(1)).getCurrentKey(Mockito.eq("k1"));37 Assert.assertEquals(mockKey, cache.getCurrentKey("k1"));38 Mockito.verify(mockProv, Mockito.times(1)).getCurrentKey(Mockito.eq("k1"));39 Thread.sleep(1200);40 Assert.assertEquals(mockKey, cache.getCurrentKey("k1"));41 Mockito.verify(mockProv, Mockito.times(2)).getCurrentKey(Mockito.eq("k1"));42 // asserting no caching when key is not known43 cache = new CachingKeyProvider(mockProv, 100, 100);44 Assert.assertEquals(null, cache.getCurrentKey("k2"));45 Mockito.verify(mockProv, Mockito.times(1)).getCurrentKey(Mockito.eq("k2"));46 Assert.assertEquals(null, cache.getCurrentKey("k2"));47 Mockito.verify(mockProv, Mockito.times(2)).getCurrentKey(Mockito.eq("k2"));48 }49 @Test50 public void testKeyVersion() throws Exception {51 KeyProvider.KeyVersion mockKey = Mockito.mock(KeyProvider.KeyVersion.class);52 KeyProvider mockProv = Mockito.mock(KeyProvider.class);53 Mockito.when(mockProv.getKeyVersion(Mockito.eq("k1@0")))54 .thenReturn(mockKey);55 Mockito.when(mockProv.getKeyVersion(Mockito.eq("k2@0"))).thenReturn(null);56 Mockito.when(mockProv.getConf()).thenReturn(new Configuration());57 KeyProvider cache = new CachingKeyProvider(mockProv, 100, 100);58 // asserting caching59 Assert.assertEquals(mockKey, cache.getKeyVersion("k1@0"));60 Mockito.verify(mockProv, Mockito.times(1))61 .getKeyVersion(Mockito.eq("k1@0"));62 Assert.assertEquals(mockKey, cache.getKeyVersion("k1@0"));63 Mockito.verify(mockProv, Mockito.times(1))64 .getKeyVersion(Mockito.eq("k1@0"));65 Thread.sleep(200);66 Assert.assertEquals(mockKey, cache.getKeyVersion("k1@0"));67 Mockito.verify(mockProv, Mockito.times(2))68 .getKeyVersion(Mockito.eq("k1@0"));69 // asserting no caching when key is not known70 cache = new CachingKeyProvider(mockProv, 100, 100);71 Assert.assertEquals(null, cache.getKeyVersion("k2@0"));72 Mockito.verify(mockProv, Mockito.times(1))73 .getKeyVersion(Mockito.eq("k2@0"));74 Assert.assertEquals(null, cache.getKeyVersion("k2@0"));75 Mockito.verify(mockProv, Mockito.times(2))76 .getKeyVersion(Mockito.eq("k2@0"));77 }78 @Test79 public void testMetadata() throws Exception {80 KeyProvider.Metadata mockMeta = Mockito.mock(KeyProvider.Metadata.class);81 KeyProvider mockProv = Mockito.mock(KeyProvider.class);82 Mockito.when(mockProv.getMetadata(Mockito.eq("k1"))).thenReturn(mockMeta);83 Mockito.when(mockProv.getMetadata(Mockito.eq("k2"))).thenReturn(null);84 Mockito.when(mockProv.getConf()).thenReturn(new Configuration());85 KeyProvider cache = new CachingKeyProvider(mockProv, 100, 100);86 // asserting caching87 Assert.assertEquals(mockMeta, cache.getMetadata("k1"));88 Mockito.verify(mockProv, Mockito.times(1)).getMetadata(Mockito.eq("k1"));89 Assert.assertEquals(mockMeta, cache.getMetadata("k1"));90 Mockito.verify(mockProv, Mockito.times(1)).getMetadata(Mockito.eq("k1"));91 Thread.sleep(200);92 Assert.assertEquals(mockMeta, cache.getMetadata("k1"));93 Mockito.verify(mockProv, Mockito.times(2)).getMetadata(Mockito.eq("k1"));94 // asserting no caching when key is not known95 cache = new CachingKeyProvider(mockProv, 100, 100);96 Assert.assertEquals(null, cache.getMetadata("k2"));97 Mockito.verify(mockProv, Mockito.times(1)).getMetadata(Mockito.eq("k2"));98 Assert.assertEquals(null, cache.getMetadata("k2"));99 Mockito.verify(mockProv, Mockito.times(2)).getMetadata(Mockito.eq("k2"));100 }101 @Test102 public void testRollNewVersion() throws Exception {103 KeyProvider.KeyVersion mockKey = Mockito.mock(KeyProvider.KeyVersion.class);104 KeyProvider mockProv = Mockito.mock(KeyProvider.class);105 Mockito.when(mockProv.getCurrentKey(Mockito.eq("k1"))).thenReturn(mockKey);106 Mockito.when(mockProv.getConf()).thenReturn(new Configuration());107 KeyProvider cache = new CachingKeyProvider(mockProv, 100, 100);108 Assert.assertEquals(mockKey, cache.getCurrentKey("k1"));109 Mockito.verify(mockProv, Mockito.times(1)).getCurrentKey(Mockito.eq("k1"));110 cache.rollNewVersion("k1");111 // asserting the cache is purged112 Assert.assertEquals(mockKey, cache.getCurrentKey("k1"));113 Mockito.verify(mockProv, Mockito.times(2)).getCurrentKey(Mockito.eq("k1"));114 cache.rollNewVersion("k1", new byte[0]);115 Assert.assertEquals(mockKey, cache.getCurrentKey("k1"));116 Mockito.verify(mockProv, Mockito.times(3)).getCurrentKey(Mockito.eq("k1"));117 }118 @Test119 public void testDeleteKey() throws Exception {120 KeyProvider.KeyVersion mockKey = Mockito.mock(KeyProvider.KeyVersion.class);121 KeyProvider mockProv = Mockito.mock(KeyProvider.class);122 Mockito.when(mockProv.getCurrentKey(Mockito.eq("k1"))).thenReturn(mockKey);123 Mockito.when(mockProv.getKeyVersion(Mockito.eq("k1@0")))124 .thenReturn(mockKey);125 Mockito.when(mockProv.getMetadata(Mockito.eq("k1"))).thenReturn(126 new KMSClientProvider.KMSMetadata("c", 0, "l", null, new Date(), 1));127 Mockito.when(mockProv.getConf()).thenReturn(new Configuration());128 KeyProvider cache = new CachingKeyProvider(mockProv, 100, 100);129 Assert.assertEquals(mockKey, cache.getCurrentKey("k1"));130 Mockito.verify(mockProv, Mockito.times(1)).getCurrentKey(Mockito.eq("k1"));131 Assert.assertEquals(mockKey, cache.getKeyVersion("k1@0"));132 Mockito.verify(mockProv, Mockito.times(1))133 .getKeyVersion(Mockito.eq("k1@0"));134 cache.deleteKey("k1");135 // asserting the cache is purged136 Assert.assertEquals(mockKey, cache.getCurrentKey("k1"));137 Mockito.verify(mockProv, Mockito.times(2)).getCurrentKey(Mockito.eq("k1"));138 Assert.assertEquals(mockKey, cache.getKeyVersion("k1@0"));139 Mockito.verify(mockProv, Mockito.times(2))140 .getKeyVersion(Mockito.eq("k1@0"));141 }142}...

Full Screen

Full Screen

Source:PartnerBookmarksReaderTest.java Github

copy

Full Screen

...6import org.junit.Before;7import org.junit.Rule;8import org.junit.Test;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();...

Full Screen

Full Screen

Source:ControllerTest.java Github

copy

Full Screen

...4import com.github.vitalibo.brickgame.core.ui.IconPanel;5import com.github.vitalibo.brickgame.game.Game;6import com.github.vitalibo.brickgame.game.Menu;7import lombok.experimental.Delegate;8import org.mockito.Mock;9import org.mockito.Mockito;10import org.mockito.MockitoAnnotations;11import org.mockito.Spy;12import org.testng.Assert;13import org.testng.annotations.BeforeMethod;14import org.testng.annotations.DataProvider;15import org.testng.annotations.Test;16import java.awt.event.KeyEvent;17import java.util.function.Consumer;18public class ControllerTest {19 @Mock20 private BrickGameFrame mockFrame;21 @Mock22 private IconPanel mockPause;23 @Mock24 private IconPanel mockSound;25 @Mock26 private BrickPanel mockBoard;27 @Mock28 private BrickPanel mockPreview;29 @Mock30 private KeyEvent mockKeyEvent;31 @Spy32 private Kernel spyKernel;33 private Controller spyController;34 @BeforeMethod35 public void setUp() {36 MockitoAnnotations.initMocks(this);37 Mockito.when(mockFrame.getPause()).thenReturn(mockPause);38 Mockito.when(mockFrame.getSound()).thenReturn(mockSound);39 Mockito.when(mockFrame.getBoard()).thenReturn(mockBoard);40 Mockito.when(mockFrame.getPreview()).thenReturn(mockPreview);41 spyController = Mockito.spy(new Controller(mockFrame, spyKernel));42 spyController.init(EmbeddedGame.class);43 }44 @DataProvider45 public Object[][] actions() {46 return new Object[][]{47 {KeyEvent.VK_UP, action(Controller::doUp)},48 {KeyEvent.VK_DOWN, action(Controller::doDown)},49 {KeyEvent.VK_LEFT, action(Controller::doLeft)},50 {KeyEvent.VK_RIGHT, action(Controller::doRight)},51 {KeyEvent.VK_SPACE, action(Controller::doRotate)}52 };53 }54 @Test(dataProvider = "actions")55 public void testDelegateKeyPressed(int keyEvent, Consumer<Controller> consumer) {56 Mockito.when(mockKeyEvent.getKeyCode()).thenReturn(keyEvent);57 spyController.keyPressed(mockKeyEvent);58 consumer.accept(Mockito.verify(spyController));59 }60 @Test(dataProvider = "actions")61 public void testNotDelegateKeyPressed(int keyEvent, Consumer<Controller> consumer) {62 Mockito.when(mockPause.get()).thenReturn(true);63 Mockito.when(mockKeyEvent.getKeyCode()).thenReturn(keyEvent);64 spyController.keyPressed(mockKeyEvent);65 consumer.accept(Mockito.verify(spyController, Mockito.never()));66 }67 @Test68 public void testChangeSound() {69 Mockito.when(mockKeyEvent.getKeyCode()).thenReturn(KeyEvent.VK_S);70 spyController.keyPressed(mockKeyEvent);71 Mockito.verify(mockSound).change();72 }73 @Test74 public void testChangePause() {75 Mockito.when(mockKeyEvent.getKeyCode()).thenReturn(KeyEvent.VK_P);76 Kernel.Job job = spyKernel.job(this, 100, o -> {77 });78 spyController.keyPressed(mockKeyEvent);79 boolean state = Mockito.verify(mockPause).change();80 Assert.assertEquals(job.isPause(), state);81 }82 @Test83 public void testReset() {84 Mockito.when(mockKeyEvent.getKeyCode()).thenReturn(KeyEvent.VK_R);85 Kernel.Job job = spyKernel.job(this, 100, o -> {86 });87 spyController.keyPressed(mockKeyEvent);88 Mockito.verify(spyController).init(Menu.class);89 Mockito.verify(spyController).unlock();90 Assert.assertTrue(job.isKilled());91 }92 private static Consumer<Controller> action(Consumer<Controller> action) {93 return action;94 }95 public static class EmbeddedGame extends Game {96 @Mock97 @Delegate98 private Game game;99 public EmbeddedGame(Context context) {100 super(context);101 MockitoAnnotations.initMocks(this);...

Full Screen

Full Screen

Source:MockitoTestExecutionListenerTests.java Github

copy

Full Screen

...12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13 * See the License for the specific language governing permissions and14 * limitations under the License.15 */16package org.springframework.boot.test.mock.mockito;17import java.io.InputStream;18import java.lang.reflect.Field;19import org.junit.Before;20import org.junit.Test;21import org.mockito.ArgumentCaptor;22import org.mockito.Captor;23import org.mockito.Mock;24import org.mockito.MockitoAnnotations;25import org.springframework.context.ApplicationContext;26import org.springframework.test.context.TestContext;27import static org.assertj.core.api.Assertions.assertThat;28import static org.mockito.BDDMockito.given;29import static org.mockito.Matchers.any;30import static org.mockito.Matchers.eq;31import static org.mockito.Mockito.mock;32import static org.mockito.Mockito.verify;33/**34 * Tests for {@link MockitoTestExecutionListener}.35 *36 * @author Phillip Webb37 */38public class MockitoTestExecutionListenerTests {39 private MockitoTestExecutionListener listener = new MockitoTestExecutionListener();40 @Mock41 private ApplicationContext applicationContext;42 @Mock43 private MockitoPostProcessor postProcessor;44 @Captor45 private ArgumentCaptor<Field> fieldCaptor;46 @Before47 public void setup() {48 MockitoAnnotations.initMocks(this);49 given(this.applicationContext.getBean(MockitoPostProcessor.class))50 .willReturn(this.postProcessor);51 }52 @Test53 public void prepareTestInstanceShouldInitMockitoAnnotations() throws Exception {54 WithMockitoAnnotations instance = new WithMockitoAnnotations();55 this.listener.prepareTestInstance(mockTestContext(instance));56 assertThat(instance.mock).isNotNull();57 assertThat(instance.captor).isNotNull();58 }59 @Test60 public void prepareTestInstanceShouldInjectMockBean() throws Exception {61 WithMockBean instance = new WithMockBean();62 this.listener.prepareTestInstance(mockTestContext(instance));63 verify(this.postProcessor).inject(this.fieldCaptor.capture(), eq(instance),64 (MockDefinition) any());65 assertThat(this.fieldCaptor.getValue().getName()).isEqualTo("mockBean");66 }67 @SuppressWarnings({ "unchecked", "rawtypes" })68 private TestContext mockTestContext(Object instance) {69 TestContext testContext = mock(TestContext.class);70 given(testContext.getTestInstance()).willReturn(instance);71 given(testContext.getTestClass()).willReturn((Class) instance.getClass());72 given(testContext.getApplicationContext()).willReturn(this.applicationContext);73 return testContext;74 }75 static class WithMockitoAnnotations {76 @Mock77 InputStream mock;78 @Captor79 ArgumentCaptor<InputStream> captor;80 }81 static class WithMockBean {82 @MockBean83 InputStream mockBean;84 }85}...

Full Screen

Full Screen

mock

Using AI Code Generation

copy

Full Screen

1package org.example;2import org.junit.Test;3import org.junit.runner.RunWith;4import org.mockito.InjectMocks;5import org.mockito.Mock;6import org.mockito.Mockito;7import org.mockito.junit.MockitoJUnitRunner;8import static org.junit.Assert.assertEquals;9import static org.mockito.Mockito.when;10@RunWith(MockitoJUnitRunner.class)11public class AppTest {12 App app;13 AppTest appTest;14 public void testApp() {15 when(app.add(10, 20)).thenReturn(30);16 assertEquals(30, appTest.add(10, 20));17 }18}19[INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ mockito-mock-method ---20[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ mockito-mock-method ---21[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ mockito-mock-method ---22[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ mockito-mock-method ---23[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ mockito-mock-method ---

Full Screen

Full Screen

mock

Using AI Code Generation

copy

Full Screen

1import org.mockito.Mockito;2import static org.mockito.Mockito.*;3import org.mockito.Matchers;4import org.mockito.ArgumentCaptor;5import org.mockito.invocation.InvocationOnMock;6import org.mockito.stubbing.Answer;7import org.mockito.verification.VerificationMode;8import org.mockito.verification.Verification

Full Screen

Full Screen

mock

Using AI Code Generation

copy

Full Screen

1import org.mockito.Mockito;2public class 1 {3 public static void main(String[] args) {4 List mockedList = Mockito.mock(List.class);5 mockedList.add("one");6 mockedList.clear();7 Mockito.verify(mockedList).add("one");8 Mockito.verify(mockedList).clear();9 }10}

Full Screen

Full Screen

mock

Using AI Code Generation

copy

Full Screen

1package com.ack.j2se.mockito;2import org.junit.Test;3import static org.junit.Assert.*;4import static org.mockito.Mockito.*;5public class MockitoTest {6 public void testMockito() {7 MyClass test = mock( MyClass.class );8 when( test.getUniqueId() ).thenReturn( 43 );9 assertEquals( test.testing( 12 ), 43 );10 test.someMethod();11 }12}13package com.ack.j2se.mockito;14public class MyClass {15 public int getUniqueId() {16 return 0;17 }18 public int testing( int i ) {19 return i * 2;20 }21 public void someMethod() {22 System.out.println( "someMethod" );23 }24}251. -> at com.ack.j2se.mockito.MockitoTest.testMockito(MockitoTest.java:24)262. -> at com.ack.j2se.mockito.MockitoTest.testMockito(MockitoTest.java:24)

Full Screen

Full Screen

mock

Using AI Code Generation

copy

Full Screen

1public class 1 {2 public static void main(String[] args) {3 List mockList = mock(List.class);4 when(mockList.get(0)).thenReturn("first");5 System.out.println(mockList.get(0));6 System.out.println(mockList.get(1));7 }8}

Full Screen

Full Screen

mock

Using AI Code Generation

copy

Full Screen

1package com.ack.j2se.mock;2import java.util.List;3import static org.mockito.Mockito.*;4public class MockingMockito {5 public static void main( String[] args ) {6 List mockedList = mock( List.class );7 mockedList.add( "one" );8 mockedList.clear();9 verify( mockedList ).add( "one" );10 verify( mockedList ).clear();11 }12}13package com.ack.j2se.mock;14import java.util.List;15import static org.mockito.Mockito.*;16public class MockingMockito {17 public static void main( String[] args ) {18 List mockedList = mock( List.class );19 mockedList.add( "one" );20 mockedList.clear();21 verify( mockedList ).add( "one" );22 verify( mockedList ).clear();23 }24}25package com.ack.j2se.mock;26import java.util.List;27import static org.mockito.Mockito.*;28public class MockingMockito {29 public static void main( String[] args ) {30 List mockedList = mock( List.class );31 mockedList.add( "one" );32 mockedList.clear();33 verify( mockedList ).add( "one" );34 verify( mockedList ).clear();35 }36}37package com.ack.j2se.mock;38import java.util.List;39import static org.mockito.Mockito.*;40public class MockingMockito {41 public static void main( String[] args ) {42 List mockedList = mock( List.class );43 mockedList.add( "one" );44 mockedList.clear();45 verify( mockedList ).add( "one" );46 verify( mockedList ).clear();47 }48}

Full Screen

Full Screen

mock

Using AI Code Generation

copy

Full Screen

1import static org.mockito.Mockito.*;2import static org.junit.Assert.*;3import org.junit.Test;4public class Test1 {5 public void test1() {6 Calculator mockCalc = mock(Calculator.class);7 when(mockCalc.add(10, 20)).thenReturn(30);8 assertEquals(mockCalc.add(10, 20), 30);9 }10}11import static org.mockito.Mockito.*;12import static org.junit.Assert.*;13import org.junit.Test;14public class Test2 {15 public void test2() {16 Calculator mockCalc = mock(Calculator.class);17 when(mockCalc.add(10, 20)).thenReturn(30);18 assertEquals(mockCalc.add(10, 20), 30);19 }20}21public class Calculator {22 public int add(int a, int b) {23 return a + b;24 }25}26BUILD SUCCESSFUL (total time: 0 seconds)27The following code shows the usage of the thenReturn() method of the stubber object:28when(mockCalc.add(10, 20)).thenReturn(30);29The following code shows the usage of the thenThrow() method of the stubber object:30when(mockCalc.add(10, 20)).thenThrow

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