Best Atoum code snippet using mock
AndroidMockTest.java
Source:AndroidMockTest.java
...12 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the13 * License for the specific language governing permissions and limitations under14 * the License.15 */16package com.google.android.testing.mocking;17import javassist.CannotCompileException;18import javassist.ClassPool;19import javassist.CtClass;20import javassist.CtMethod;21import javassist.Modifier;22import javassist.NotFoundException;23import javassist.expr.ExprEditor;24import javassist.expr.MethodCall;25import junit.framework.TestCase;26import org.easymock.Capture;27import org.easymock.IAnswer;28import org.easymock.LogicalOperator;29import org.easymock.internal.matchers.Equals;30import java.io.IOException;31import java.io.InputStream;32import java.io.ObjectInput;33import java.util.ArrayList;34import java.util.Arrays;35import java.util.Calendar;36import java.util.List;37import java.util.Locale;38import java.util.Map;39import java.util.SimpleTimeZone;40import java.util.Vector;41/**42 * Tests for the AndroidMock class.43 * 44 * @author swoodward@google.com (Stephen Woodward)45 */46public class AndroidMockTest extends TestCase {47 private List<String> notForwardedMethods =48 new ArrayList<String>(Arrays.asList(new String[] {49 "com.google.android.testing.mocking.AndroidMock.getInterfaceFor(java.lang.Class)",50 "com.google.android.testing.mocking.AndroidMock.getSubclassNameFor(java.lang.Class)",51 "com.google.android.testing.mocking.AndroidMock.getSubclassFor(java.lang.Class,"52 + "java.lang.Class,java.lang.Object)",53 "com.google.android.testing.mocking.AndroidMock.getInterfaceNameFor(java.lang.Class)",54 "com.google.android.testing.mocking.AndroidMock.createStrictMock("55 + "java.lang.Class,java.lang.Object[])",56 "com.google.android.testing.mocking.AndroidMock.createStrictMock("57 + "java.lang.String,java.lang.Class,java.lang.Object[])",58 "com.google.android.testing.mocking.AndroidMock.createMock("59 + "java.lang.Class,java.lang.Object[])",60 "com.google.android.testing.mocking.AndroidMock.createMock("61 + "java.lang.String,java.lang.Class,java.lang.Object[])",62 "com.google.android.testing.mocking.AndroidMock.createNiceMock("63 + "java.lang.Class,java.lang.Object[])",64 "com.google.android.testing.mocking.AndroidMock.createNiceMock("65 + "java.lang.String,java.lang.Class,java.lang.Object[])"}));66 private CtMethod[] getForwardedMethods() throws NotFoundException {67 List<CtMethod> methods =68 new ArrayList<CtMethod>(Arrays.asList(getAndroidMockCtClass().getDeclaredMethods()));69 // Get a copy for safe removal of elements during iteration.70 for (CtMethod method : Arrays.asList(methods.toArray(new CtMethod[0]))) {71 if (notForwardedMethods.contains(method.getLongName())72 || !Modifier.isPublic(method.getModifiers())) {73 methods.remove(method);74 }75 }76 return methods.toArray(new CtMethod[0]);77 }78 private CtClass getAndroidMockCtClass() throws NotFoundException {79 return ClassPool.getDefault().get("com.google.android.testing.mocking.AndroidMock");80 }81 private void compileClasses(List<GeneratedClassFile> mockClasses) throws NotFoundException {82 for (GeneratedClassFile clazz : mockClasses) {83 CtClass ctClass;84 ctClass = ClassPool.getDefault().get(clazz.getClassName());85 try {86 ctClass.toClass();87 } catch (CannotCompileException e) {88 // Just ignore -- this will happen for every class used in more than one test.89 }90 }91 }92 public void testIsUnboxableToPrimitiveAllPrimitives() {93 assertTrue(AndroidMock.isUnboxableToPrimitive(Integer.TYPE, new Integer(42), true));94 assertTrue(AndroidMock.isUnboxableToPrimitive(Long.TYPE, new Long(42L), true));95 assertTrue(AndroidMock.isUnboxableToPrimitive(Short.TYPE, new Short((short) 42), true));96 assertTrue(AndroidMock.isUnboxableToPrimitive(Byte.TYPE, new Byte((byte) 42), true));97 assertTrue(AndroidMock.isUnboxableToPrimitive(Boolean.TYPE, Boolean.TRUE, true));98 assertTrue(AndroidMock.isUnboxableToPrimitive(Float.TYPE, new Float(42.0f), true));99 assertTrue(AndroidMock.isUnboxableToPrimitive(Double.TYPE, new Double(42.0), true));100 assertTrue(AndroidMock.isUnboxableToPrimitive(Character.TYPE, new Character('a'), true));101 assertTrue(AndroidMock.isUnboxableToPrimitive(Integer.TYPE, 42, true));102 assertTrue(AndroidMock.isUnboxableToPrimitive(Long.TYPE, 42L, true));103 assertTrue(AndroidMock.isUnboxableToPrimitive(Short.TYPE, (short) 42, true));104 assertTrue(AndroidMock.isUnboxableToPrimitive(Byte.TYPE, (byte) 42, true));105 assertTrue(AndroidMock.isUnboxableToPrimitive(Boolean.TYPE, true, true));106 assertTrue(AndroidMock.isUnboxableToPrimitive(Float.TYPE, 42.0f, true));107 assertTrue(AndroidMock.isUnboxableToPrimitive(Double.TYPE, 42.0, true));108 assertTrue(AndroidMock.isUnboxableToPrimitive(Character.TYPE, 'a', true));109 }110 public void testIsUnboxableToPrimitiveIsObject() {111 assertFalse(AndroidMock.isUnboxableToPrimitive(Integer.TYPE, new Object(), false));112 }113 public void testIsUnboxableToPrimitiveAllWideningPrimitives() {114 Object[] testValues =115 new Object[] {new Byte((byte) 42), new Short((short) 42), new Integer(42), new Long(42L),116 new Float(42.0f), new Double(42.0), new Character('a'), Boolean.TRUE};117 boolean[] byteExpected = new boolean[] {true, false, false, false, false, false, false, false};118 boolean[] shortExpected = new boolean[] {true, true, false, false, false, false, true, false};119 boolean[] intExpected = new boolean[] {true, true, true, false, false, false, true, false};120 boolean[] longExpected = new boolean[] {true, true, true, true, false, false, true, false};121 boolean[] floatExpected = new boolean[] {true, true, true, false, true, false, true, false};122 boolean[] doubleExpected = new boolean[] {true, true, true, true, true, true, true, false};123 boolean[] charExpected = new boolean[] {true, true, true, false, false, false, true, false};124 boolean[] booleanExpected =125 new boolean[] {false, false, false, false, false, false, false, true};126 for (int i = 0; i < testValues.length; ++i) {127 assertEquals("Convert byte from " + testValues[i].getClass(), byteExpected[i], AndroidMock128 .isUnboxableToPrimitive(Byte.TYPE, testValues[i], false));129 assertEquals("Convert short from " + testValues[i].getClass(), shortExpected[i], AndroidMock130 .isUnboxableToPrimitive(Short.TYPE, testValues[i], false));131 assertEquals("Convert int from " + testValues[i].getClass(), intExpected[i], AndroidMock132 .isUnboxableToPrimitive(Integer.TYPE, testValues[i], false));133 assertEquals("Convert long from " + testValues[i].getClass(), longExpected[i], AndroidMock134 .isUnboxableToPrimitive(Long.TYPE, testValues[i], false));135 assertEquals("Convert float from " + testValues[i].getClass(), floatExpected[i], AndroidMock136 .isUnboxableToPrimitive(Float.TYPE, testValues[i], false));137 assertEquals("Convert double from " + testValues[i].getClass(), doubleExpected[i],138 AndroidMock.isUnboxableToPrimitive(Double.TYPE, testValues[i], false));139 assertEquals("Convert char from " + testValues[i].getClass(), charExpected[i], AndroidMock140 .isUnboxableToPrimitive(Character.TYPE, testValues[i], false));141 assertEquals("Convert boolean from " + testValues[i].getClass(), booleanExpected[i],142 AndroidMock.isUnboxableToPrimitive(Boolean.TYPE, testValues[i], false));143 }144 }145 public void testIsUnboxableToPrimitiveNotPrimitive() {146 try {147 AndroidMock.isUnboxableToPrimitive(Object.class, Object.class, false);148 fail("Exception should have been thrown");149 } catch (IllegalArgumentException e) {150 // expected151 }152 }153 public void testCreateMock() throws ClassNotFoundException, IOException, CannotCompileException,154 NotFoundException {155 List<GeneratedClassFile> mockClasses =156 new AndroidMockGenerator().createMocksForClass(Vector.class);157 compileClasses(mockClasses);158 Vector<String> mockVector = AndroidMock.createMock(Vector.class);159 AndroidMock.expect(mockVector.get(0)).andReturn("Hello World");160 AndroidMock.replay(mockVector);161 assertEquals("Hello World", mockVector.get(0).toString());162 AndroidMock.verify(mockVector);163 }164 public void testCreateMockUsingParameters() throws ClassNotFoundException, IOException,165 CannotCompileException, NotFoundException {166 List<GeneratedClassFile> mockClasses =167 new AndroidMockGenerator().createMocksForClass(SimpleTimeZone.class);168 compileClasses(mockClasses);169 SimpleTimeZone mockTimeZone = AndroidMock.createMock(SimpleTimeZone.class, 0, "GMT");170 AndroidMock.expect(mockTimeZone.getRawOffset()).andReturn(42);171 AndroidMock.replay(mockTimeZone);172 assertEquals(42, mockTimeZone.getRawOffset());173 AndroidMock.verify(mockTimeZone);174 }175 public void testCreateMockUsingProtectedConstructors() throws ClassNotFoundException,176 IOException, CannotCompileException, NotFoundException {177 List<GeneratedClassFile> mockClasses =178 new AndroidMockGenerator().createMocksForClass(Calendar.class);179 compileClasses(mockClasses);180 Calendar mockCalendar = AndroidMock.createMock(Calendar.class);181 AndroidMock.expect(mockCalendar.getGreatestMinimum(1)).andReturn(42);182 AndroidMock.replay(mockCalendar);183 assertEquals(42, mockCalendar.getGreatestMinimum(1));184 AndroidMock.verify(mockCalendar);185 // Just don't explode186 Calendar newMockCalendar =187 AndroidMock.createMock(Calendar.class, new SimpleTimeZone(1, "GMT"), Locale.UK);188 }189 public void testCreateMockUsingCastableParameters() throws ClassNotFoundException, IOException,190 CannotCompileException, NotFoundException {191 List<GeneratedClassFile> mockClasses =192 new AndroidMockGenerator().createMocksForClass(SimpleTimeZone.class);193 compileClasses(mockClasses);194 SimpleTimeZone mockTimeZone = AndroidMock.createMock(SimpleTimeZone.class, 'a', "GMT");195 AndroidMock.expect(mockTimeZone.getRawOffset()).andReturn(42);196 AndroidMock.replay(mockTimeZone);197 assertEquals(42, mockTimeZone.getRawOffset());198 AndroidMock.verify(mockTimeZone);199 }200 public void testCreateMockUsingUnusableParameters() throws ClassNotFoundException, IOException,201 CannotCompileException, NotFoundException {202 List<GeneratedClassFile> mockClasses =203 new AndroidMockGenerator().createMocksForClass(SimpleTimeZone.class);204 compileClasses(mockClasses);205 try {206 SimpleTimeZone mockTimeZone = AndroidMock.createMock(SimpleTimeZone.class, "GMT");207 fail("Excepted an IllegalArgumentException for incorrect number of constructor parameters");208 } catch (IllegalArgumentException e) {209 // Expected210 }211 try {212 SimpleTimeZone mockTimeZone = AndroidMock.createMock(SimpleTimeZone.class, 0, null);213 fail("Excepted an IllegalArgumentException for indeterminate null constructor parameters");214 } catch (IllegalArgumentException e) {215 // Expected216 }217 try {218 SimpleTimeZone mockTimeZone = AndroidMock.createMock(SimpleTimeZone.class, 0, new Object());219 fail("Excepted an IllegalArgumentException for incorrect constructor parameters");220 } catch (IllegalArgumentException e) {221 // Expected222 }223 }224 public void testCreateMockUsingInterface() throws ClassNotFoundException, IOException,225 CannotCompileException, NotFoundException {226 List<GeneratedClassFile> mockClasses =227 new AndroidMockGenerator().createMocksForClass(Map.class);228 compileClasses(mockClasses);229 Map<String, String> mockMap = AndroidMock.createMock(Map.class);230 AndroidMock.expect(mockMap.get("key")).andReturn("Hello World");231 AndroidMock.replay(mockMap);232 assertEquals("Hello World", mockMap.get("key"));233 AndroidMock.verify(mockMap);234 }235 public void testCreateMockUsingClass() throws ClassNotFoundException, IOException,236 CannotCompileException, NotFoundException {237 List<GeneratedClassFile> mockClasses =238 new AndroidMockGenerator().createMocksForClass(Vector.class);239 compileClasses(mockClasses);240 Vector<String> mockVector = AndroidMock.createMock(Vector.class);241 AndroidMock.expect(mockVector.get(0)).andReturn("Hello World");242 AndroidMock.replay(mockVector);243 assertEquals("Hello World", mockVector.get(0).toString());244 AndroidMock.verify(mockVector);245 }246 public void testCreateNiceMock() throws ClassNotFoundException, IOException,247 CannotCompileException, NotFoundException {248 List<GeneratedClassFile> mockClasses =249 new AndroidMockGenerator().createMocksForClass(Vector.class);250 compileClasses(mockClasses);251 Vector<String> mockVector = AndroidMock.createNiceMock(Vector.class);252 AndroidMock.expect(mockVector.get(0)).andReturn("Hello World");253 AndroidMock.replay(mockVector);254 assertEquals("Hello World", mockVector.get(0).toString());255 AndroidMock.verify(mockVector);256 }257 public void testCreateNiceMockUsingUnusableParameters() throws ClassNotFoundException,258 IOException, CannotCompileException, NotFoundException {259 List<GeneratedClassFile> mockClasses =260 new AndroidMockGenerator().createMocksForClass(SimpleTimeZone.class);261 compileClasses(mockClasses);262 try {263 SimpleTimeZone mockTimeZone = AndroidMock.createNiceMock(SimpleTimeZone.class, "GMT");264 fail("Excepted an IllegalArgumentException for incorrect number of constructor parameters");265 } catch (IllegalArgumentException e) {266 // Expected267 }268 try {269 SimpleTimeZone mockTimeZone = AndroidMock.createNiceMock(SimpleTimeZone.class, 0, null);270 fail("Excepted an IllegalArgumentException for indeterminate null constructor parameters");271 } catch (IllegalArgumentException e) {272 // Expected273 }274 try {275 SimpleTimeZone mockTimeZone =276 AndroidMock.createNiceMock(SimpleTimeZone.class, 0, new Object());277 fail("Excepted an IllegalArgumentException for incorrect constructor parameters");278 } catch (IllegalArgumentException e) {279 // Expected280 }281 }282 public void testCreateNiceMockUsingParameters() throws ClassNotFoundException, IOException,283 CannotCompileException, NotFoundException {284 List<GeneratedClassFile> mockClasses =285 new AndroidMockGenerator().createMocksForClass(SimpleTimeZone.class);286 compileClasses(mockClasses);287 SimpleTimeZone mockTimeZone = AndroidMock.createNiceMock(SimpleTimeZone.class, 0, "GMT");288 AndroidMock.expect(mockTimeZone.getRawOffset()).andReturn(42);289 AndroidMock.replay(mockTimeZone);290 assertEquals(42, mockTimeZone.getRawOffset());291 AndroidMock.verify(mockTimeZone);292 }293 public void testCreateNiceMockUsingCastableParameters() throws ClassNotFoundException,294 IOException, CannotCompileException, NotFoundException {295 List<GeneratedClassFile> mockClasses =296 new AndroidMockGenerator().createMocksForClass(SimpleTimeZone.class);297 compileClasses(mockClasses);298 SimpleTimeZone mockTimeZone = AndroidMock.createNiceMock(SimpleTimeZone.class, 'a', "GMT");299 AndroidMock.expect(mockTimeZone.getRawOffset()).andReturn(42);300 AndroidMock.replay(mockTimeZone);301 assertEquals(42, mockTimeZone.getRawOffset());302 AndroidMock.verify(mockTimeZone);303 }304 public void testCreateNiceMockUsingInterface() throws ClassNotFoundException, IOException,305 CannotCompileException, NotFoundException {306 List<GeneratedClassFile> mockClasses =307 new AndroidMockGenerator().createMocksForClass(Map.class);308 compileClasses(mockClasses);309 Map<String, String> mockMap = AndroidMock.createNiceMock(Map.class);310 AndroidMock.expect(mockMap.get("key")).andReturn("Hello World");311 AndroidMock.replay(mockMap);312 assertEquals("Hello World", mockMap.get("key"));313 AndroidMock.verify(mockMap);314 }315 public void testCreateNiceMockUsingClass() throws ClassNotFoundException, IOException,316 CannotCompileException, NotFoundException {317 List<GeneratedClassFile> mockClasses =318 new AndroidMockGenerator().createMocksForClass(Vector.class);319 compileClasses(mockClasses);320 Vector<String> mockVector = AndroidMock.createNiceMock(Vector.class);321 AndroidMock.expect(mockVector.get(0)).andReturn("Hello World");322 AndroidMock.replay(mockVector);323 assertEquals("Hello World", mockVector.get(0).toString());324 AndroidMock.verify(mockVector);325 }326 public void testCreateStrictMock() throws ClassNotFoundException, IOException,327 CannotCompileException, NotFoundException {328 List<GeneratedClassFile> mockClasses =329 new AndroidMockGenerator().createMocksForClass(Vector.class);330 compileClasses(mockClasses);331 Vector<String> mockVector = AndroidMock.createStrictMock(Vector.class);332 AndroidMock.expect(mockVector.get(0)).andReturn("Hello World");333 AndroidMock.replay(mockVector);334 assertEquals("Hello World", mockVector.get(0).toString());335 AndroidMock.verify(mockVector);336 }337 public void testCreateStrictMockUsingUnusableParameters() throws ClassNotFoundException,338 IOException, CannotCompileException, NotFoundException {339 List<GeneratedClassFile> mockClasses =340 new AndroidMockGenerator().createMocksForClass(SimpleTimeZone.class);341 compileClasses(mockClasses);342 try {343 SimpleTimeZone mockTimeZone = AndroidMock.createStrictMock(SimpleTimeZone.class, "GMT");344 fail("Excepted an IllegalArgumentException for incorrect number of constructor parameters");345 } catch (IllegalArgumentException e) {346 // Expected347 }348 try {349 SimpleTimeZone mockTimeZone = AndroidMock.createStrictMock(SimpleTimeZone.class, 0, null);350 fail("Excepted an IllegalArgumentException for indeterminate null constructor parameters");351 } catch (IllegalArgumentException e) {352 // Expected353 }354 try {355 SimpleTimeZone mockTimeZone =356 AndroidMock.createStrictMock(SimpleTimeZone.class, 0, new Object());357 fail("Excepted an IllegalArgumentException for incorrect constructor parameters");358 } catch (IllegalArgumentException e) {359 // Expected360 }361 }362 public void testCreateStrictMockUsingParameters() throws ClassNotFoundException, IOException,363 CannotCompileException, NotFoundException {364 List<GeneratedClassFile> mockClasses =365 new AndroidMockGenerator().createMocksForClass(SimpleTimeZone.class);366 compileClasses(mockClasses);367 SimpleTimeZone mockTimeZone = AndroidMock.createStrictMock(SimpleTimeZone.class, 0, "GMT");368 AndroidMock.expect(mockTimeZone.getRawOffset()).andReturn(42);369 AndroidMock.replay(mockTimeZone);370 assertEquals(42, mockTimeZone.getRawOffset());371 AndroidMock.verify(mockTimeZone);372 }373 public void testCreateStrictMockUsingCastableParameters() throws ClassNotFoundException,374 IOException, CannotCompileException, NotFoundException {375 List<GeneratedClassFile> mockClasses =376 new AndroidMockGenerator().createMocksForClass(SimpleTimeZone.class);377 compileClasses(mockClasses);378 SimpleTimeZone mockTimeZone = AndroidMock.createStrictMock(SimpleTimeZone.class, 'a', "GMT");379 AndroidMock.expect(mockTimeZone.getRawOffset()).andReturn(42);380 AndroidMock.replay(mockTimeZone);381 assertEquals(42, mockTimeZone.getRawOffset());382 AndroidMock.verify(mockTimeZone);383 }384 public void testCreateStrictMockUsingInterface() throws ClassNotFoundException, IOException,385 CannotCompileException, NotFoundException {386 List<GeneratedClassFile> mockClasses =387 new AndroidMockGenerator().createMocksForClass(Map.class);388 compileClasses(mockClasses);389 Map<String, String> mockMap = AndroidMock.createStrictMock(Map.class);390 AndroidMock.expect(mockMap.get("key")).andReturn("Hello World");391 AndroidMock.replay(mockMap);392 assertEquals("Hello World", mockMap.get("key"));393 AndroidMock.verify(mockMap);394 }395 public void testCreateStrictMockUsingClass() throws ClassNotFoundException, IOException,396 CannotCompileException, NotFoundException {397 List<GeneratedClassFile> mockClasses =398 new AndroidMockGenerator().createMocksForClass(Vector.class);399 compileClasses(mockClasses);400 Vector<String> mockVector = AndroidMock.createStrictMock(Vector.class);401 AndroidMock.expect(mockVector.get(0)).andReturn("Hello World");402 AndroidMock.replay(mockVector);403 assertEquals("Hello World", mockVector.get(0).toString());404 AndroidMock.verify(mockVector);405 }406 public void testCreateMockConstructorDoesWorkOnAllReturnTypes() throws ClassNotFoundException,407 IOException, CannotCompileException, NotFoundException {408 List<GeneratedClassFile> mockClasses =409 new AndroidMockGenerator().createMocksForClass(ClassDoesWorkInConstructor.class);410 compileClasses(mockClasses);411 ClassDoesWorkInConstructor mock = AndroidMock.createMock(ClassDoesWorkInConstructor.class);412 }413 public void testAllForwardedMethods() throws CannotCompileException, NotFoundException {414 for (CtMethod method : getForwardedMethods()) {415 MethodVerifier verifier = new MethodVerifier(method);416 // CtMethod.instrument Causes every instruction in the method to be417 // inspected, and passed to418 // the MethodVerifier callback (extends javassist.expr.ExprEditor). We419 // want to verify that420 // the expected EasyMock method is called at least once in each421 // AndroidMock method.422 method.instrument(verifier);423 assertTrue(method.getLongName() + " not called.", verifier.expectedMethodCalled());424 }425 }426 public void testCheckOrder() throws ClassNotFoundException, IOException, CannotCompileException,427 NotFoundException {428 List<GeneratedClassFile> mockClasses =429 new AndroidMockGenerator().createMocksForClass(Vector.class);430 compileClasses(mockClasses);431 Vector<?> mockVector = AndroidMock.createMock(Vector.class);432 AndroidMock.checkOrder(mockVector, false);433 AndroidMock.checkOrder(AndroidMock.createMock(Map.class), false);434 }435 public void testVerify() throws ClassNotFoundException, IOException, CannotCompileException,436 NotFoundException {437 List<GeneratedClassFile> mockClasses =438 new AndroidMockGenerator().createMocksForClass(Vector.class);439 compileClasses(mockClasses);440 Vector<?> mockVector = AndroidMock.createMock(Vector.class);441 AndroidMock.replay(mockVector);442 AndroidMock.verify(mockVector);443 Map<?, ?> mockMap = AndroidMock.createMock(Map.class);444 AndroidMock.replay(mockMap);445 AndroidMock.verify(mockMap);446 }447 public void testResetToStrict() throws ClassNotFoundException, IOException,448 CannotCompileException, NotFoundException {449 List<GeneratedClassFile> mockClasses =450 new AndroidMockGenerator().createMocksForClass(Vector.class);451 compileClasses(mockClasses);452 Vector<?> mockVector = AndroidMock.createMock(Vector.class);453 AndroidMock.resetToStrict(mockVector);454 Map<?, ?> mockMap = AndroidMock.createMock(Map.class);455 AndroidMock.resetToStrict(mockMap);456 }457 public void testResetToDefault() throws ClassNotFoundException, IOException,458 CannotCompileException, NotFoundException {459 List<GeneratedClassFile> mockClasses =460 new AndroidMockGenerator().createMocksForClass(Vector.class);461 compileClasses(mockClasses);462 Vector<?> mockVector = AndroidMock.createMock(Vector.class);463 AndroidMock.resetToDefault(mockVector);464 Map<?, ?> mockMap = AndroidMock.createMock(Map.class);465 AndroidMock.resetToDefault(mockMap);466 }467 public void testResetToNice() throws ClassNotFoundException, IOException,468 CannotCompileException, NotFoundException {469 List<GeneratedClassFile> mockClasses =470 new AndroidMockGenerator().createMocksForClass(Vector.class);471 compileClasses(mockClasses);472 Vector<?> mockVector = AndroidMock.createMock(Vector.class);473 AndroidMock.resetToNice(mockVector);474 Map<?, ?> mockMap = AndroidMock.createMock(Map.class);475 AndroidMock.resetToNice(mockMap);476 }477 public void testReset() throws ClassNotFoundException, IOException, CannotCompileException,478 NotFoundException {479 List<GeneratedClassFile> mockClasses =480 new AndroidMockGenerator().createMocksForClass(Vector.class);481 compileClasses(mockClasses);482 Vector<?> mockVector = AndroidMock.createMock(Vector.class);483 AndroidMock.reset(mockVector);484 Map<?, ?> mockMap = AndroidMock.createMock(Map.class);485 AndroidMock.reset(mockMap);486 }487 public void testReplay() throws ClassNotFoundException, IOException, CannotCompileException,488 NotFoundException {489 List<GeneratedClassFile> mockClasses =490 new AndroidMockGenerator().createMocksForClass(Vector.class);491 compileClasses(mockClasses);492 Vector<?> mockVector = AndroidMock.createMock(Vector.class);493 AndroidMock.replay(mockVector);494 Map<?, ?> mockMap = AndroidMock.createMock(Map.class);495 AndroidMock.replay(mockMap);496 }497 public void testExpect() {498 Map<?, ?> mockMap = AndroidMock.createMock(Map.class);499 mockMap.clear();500 AndroidMock.expect(null);501 AndroidMock.replay(mockMap);502 }503 public void testExpectLastCall() {504 Map<?, ?> mockMap = AndroidMock.createMock(Map.class);505 mockMap.clear();506 AndroidMock.expectLastCall();507 AndroidMock.replay(mockMap);508 }509 public void testAnyBoolean() {510 Map<?, ?> mockMap = AndroidMock.createMock(Map.class);511 AndroidMock.expect(mockMap.get(AndroidMock.anyBoolean())).andReturn(null);512 AndroidMock.replay(mockMap);513 }514 public void testAnyByte() {515 Map<?, ?> mockMap = AndroidMock.createMock(Map.class);516 AndroidMock.expect(mockMap.get(AndroidMock.anyByte())).andReturn(null);517 AndroidMock.replay(mockMap);518 }519 public void testAnyChar() {520 Map<?, ?> mockMap = AndroidMock.createMock(Map.class);521 AndroidMock.expect(mockMap.get(AndroidMock.anyChar())).andReturn(null);522 AndroidMock.replay(mockMap);523 }524 public void testAnyInt() {525 Map<?, ?> mockMap = AndroidMock.createMock(Map.class);526 AndroidMock.expect(mockMap.get(AndroidMock.anyInt())).andReturn(null);527 AndroidMock.replay(mockMap);528 }529 public void testAnyLong() {530 Map<?, ?> mockMap = AndroidMock.createMock(Map.class);531 AndroidMock.expect(mockMap.get(AndroidMock.anyLong())).andReturn(null);532 AndroidMock.replay(mockMap);533 }534 public void testAnyFloat() {535 Map<?, ?> mockMap = AndroidMock.createMock(Map.class);536 AndroidMock.expect(mockMap.get(AndroidMock.anyFloat())).andReturn(null);537 AndroidMock.replay(mockMap);538 }539 public void testAnyDouble() {540 Map<?, ?> mockMap = AndroidMock.createMock(Map.class);541 AndroidMock.expect(mockMap.get(AndroidMock.anyDouble())).andReturn(null);542 AndroidMock.replay(mockMap);543 }544 public void testAnyShort() {545 Map<?, ?> mockMap = AndroidMock.createMock(Map.class);546 AndroidMock.expect(mockMap.get(AndroidMock.anyShort())).andReturn(null);547 AndroidMock.replay(mockMap);548 }549 public void testAnyObject() {550 Map<?, ?> mockMap = AndroidMock.createMock(Map.class);551 AndroidMock.expect(mockMap.get(AndroidMock.anyObject())).andReturn(null);552 AndroidMock.replay(mockMap);553 }554 public void testGeq() {555 Map<?, ?> mockMap = AndroidMock.createMock(Map.class);556 AndroidMock.expect(mockMap.get(AndroidMock.geq((byte) 0))).andReturn(null);557 AndroidMock.expect(mockMap.get(AndroidMock.geq((short) 0))).andReturn(null);558 AndroidMock.expect(mockMap.get(AndroidMock.geq(0))).andReturn(null);559 AndroidMock.expect(mockMap.get(AndroidMock.geq(0L))).andReturn(null);560 AndroidMock.expect(mockMap.get(AndroidMock.geq(0.0))).andReturn(null);561 AndroidMock.expect(mockMap.get(AndroidMock.geq(0.0f))).andReturn(null);562 AndroidMock.expect(mockMap.get(AndroidMock.geq("Hi"))).andReturn(null);563 AndroidMock.replay(mockMap);564 }565 public void testLeq() {566 Map<?, ?> mockMap = AndroidMock.createMock(Map.class);567 AndroidMock.expect(mockMap.get(AndroidMock.leq((byte) 0))).andReturn(null);568 AndroidMock.expect(mockMap.get(AndroidMock.leq((short) 0))).andReturn(null);569 AndroidMock.expect(mockMap.get(AndroidMock.leq(0))).andReturn(null);570 AndroidMock.expect(mockMap.get(AndroidMock.leq(0L))).andReturn(null);571 AndroidMock.expect(mockMap.get(AndroidMock.leq(0.0))).andReturn(null);572 AndroidMock.expect(mockMap.get(AndroidMock.leq(0.0f))).andReturn(null);573 AndroidMock.expect(mockMap.get(AndroidMock.leq("Hi"))).andReturn(null);574 AndroidMock.replay(mockMap);575 }576 public void testGt() {577 Map<?, ?> mockMap = AndroidMock.createMock(Map.class);578 AndroidMock.expect(mockMap.get(AndroidMock.gt((byte) 0))).andReturn(null);579 AndroidMock.expect(mockMap.get(AndroidMock.gt((short) 0))).andReturn(null);580 AndroidMock.expect(mockMap.get(AndroidMock.gt(0))).andReturn(null);581 AndroidMock.expect(mockMap.get(AndroidMock.gt(0L))).andReturn(null);582 AndroidMock.expect(mockMap.get(AndroidMock.gt(0.0))).andReturn(null);583 AndroidMock.expect(mockMap.get(AndroidMock.gt(0.0f))).andReturn(null);584 AndroidMock.expect(mockMap.get(AndroidMock.gt("Hi"))).andReturn(null);585 AndroidMock.replay(mockMap);586 }587 public void testLt() {588 Map<?, ?> mockMap = AndroidMock.createMock(Map.class);589 AndroidMock.expect(mockMap.get(AndroidMock.lt((byte) 0))).andReturn(null);590 AndroidMock.expect(mockMap.get(AndroidMock.lt((short) 0))).andReturn(null);591 AndroidMock.expect(mockMap.get(AndroidMock.lt(0))).andReturn(null);592 AndroidMock.expect(mockMap.get(AndroidMock.lt(0L))).andReturn(null);593 AndroidMock.expect(mockMap.get(AndroidMock.lt(0.0))).andReturn(null);594 AndroidMock.expect(mockMap.get(AndroidMock.lt(0.0f))).andReturn(null);595 AndroidMock.expect(mockMap.get(AndroidMock.lt("Hi"))).andReturn(null);596 AndroidMock.replay(mockMap);597 }598 public void testIsA() {599 Map<?, ?> mockMap = AndroidMock.createMock(Map.class);600 AndroidMock.expect(mockMap.get(AndroidMock.isA(String.class))).andReturn(null);601 AndroidMock.replay(mockMap);602 }603 public void testContains() {604 Map<?, ?> mockMap = AndroidMock.createMock(Map.class);605 AndroidMock.expect(mockMap.get(AndroidMock.contains("hi"))).andReturn(null);606 AndroidMock.replay(mockMap);607 }608 public void testAnd() {609 Map<?, ?> mockMap = AndroidMock.createMock(Map.class);610 AndroidMock.expect(mockMap.get(AndroidMock.and(AndroidMock.eq(true), AndroidMock.eq(true))))611 .andReturn(null);612 AndroidMock.expect(613 mockMap.get(AndroidMock.and(AndroidMock.eq((byte) 0), AndroidMock.eq((byte) 0))))614 .andReturn(null);615 AndroidMock.expect(616 mockMap.get(AndroidMock.and(AndroidMock.eq((short) 0), AndroidMock.eq((short) 0))))617 .andReturn(null);618 AndroidMock.expect(mockMap.get(AndroidMock.and(AndroidMock.eq(0), AndroidMock.eq(0))))619 .andReturn(null);620 AndroidMock.expect(mockMap.get(AndroidMock.and(AndroidMock.eq(0L), AndroidMock.eq(0L))))621 .andReturn(null);622 AndroidMock.expect(mockMap.get(AndroidMock.and(AndroidMock.eq(0.0), AndroidMock.eq(0.0))))623 .andReturn(null);624 AndroidMock.expect(mockMap.get(AndroidMock.and(AndroidMock.eq(0.0f), AndroidMock.eq(0.0f))))625 .andReturn(null);626 AndroidMock.expect(mockMap.get(AndroidMock.and(AndroidMock.eq("hi"), AndroidMock.eq("hi"))))627 .andReturn(null);628 AndroidMock.expect(mockMap.get(AndroidMock.and(AndroidMock.eq('a'), AndroidMock.eq('a'))))629 .andReturn(null);630 AndroidMock.replay(mockMap);631 }632 public void testOr() {633 Map<?, ?> mockMap = AndroidMock.createMock(Map.class);634 AndroidMock.expect(mockMap.get(AndroidMock.or(AndroidMock.eq(true), AndroidMock.eq(true))))635 .andReturn(null);636 AndroidMock.expect(637 mockMap.get(AndroidMock.or(AndroidMock.eq((byte) 0), AndroidMock.eq((byte) 0))))638 .andReturn(null);639 AndroidMock.expect(640 mockMap.get(AndroidMock.or(AndroidMock.eq((short) 0), AndroidMock.eq((short) 0))))641 .andReturn(null);642 AndroidMock.expect(mockMap.get(AndroidMock.or(AndroidMock.eq(0), AndroidMock.eq(0))))643 .andReturn(null);644 AndroidMock.expect(mockMap.get(AndroidMock.or(AndroidMock.eq(0L), AndroidMock.eq(0L))))645 .andReturn(null);646 AndroidMock.expect(mockMap.get(AndroidMock.or(AndroidMock.eq(0.0), AndroidMock.eq(0.0))))647 .andReturn(null);648 AndroidMock.expect(mockMap.get(AndroidMock.or(AndroidMock.eq(0.0f), AndroidMock.eq(0.0f))))649 .andReturn(null);650 AndroidMock.expect(mockMap.get(AndroidMock.or(AndroidMock.eq("hi"), AndroidMock.eq("hi"))))651 .andReturn(null);652 AndroidMock.expect(mockMap.get(AndroidMock.or(AndroidMock.eq('a'), AndroidMock.eq('a'))))653 .andReturn(null);654 AndroidMock.replay(mockMap);655 }656 public void testNot() {657 Map<?, ?> mockMap = AndroidMock.createMock(Map.class);658 AndroidMock.expect(mockMap.get(AndroidMock.not(AndroidMock.eq(true)))).andReturn(null);659 AndroidMock.expect(mockMap.get(AndroidMock.not(AndroidMock.eq((byte) 0)))).andReturn(null);660 AndroidMock.expect(mockMap.get(AndroidMock.not(AndroidMock.eq((short) 0)))).andReturn(null);661 AndroidMock.expect(mockMap.get(AndroidMock.not(AndroidMock.eq(0)))).andReturn(null);662 AndroidMock.expect(mockMap.get(AndroidMock.not(AndroidMock.eq(0L)))).andReturn(null);663 AndroidMock.expect(mockMap.get(AndroidMock.not(AndroidMock.eq(0.0)))).andReturn(null);664 AndroidMock.expect(mockMap.get(AndroidMock.not(AndroidMock.eq(0.0f)))).andReturn(null);665 AndroidMock.expect(mockMap.get(AndroidMock.not(AndroidMock.eq("hi")))).andReturn(null);666 AndroidMock.expect(mockMap.get(AndroidMock.not(AndroidMock.eq('a')))).andReturn(null);667 AndroidMock.replay(mockMap);668 }669 public void testEq() {670 Map<?, ?> mockMap = AndroidMock.createMock(Map.class);671 AndroidMock.expect(mockMap.get(AndroidMock.eq(true))).andReturn(null);672 AndroidMock.expect(mockMap.get(AndroidMock.eq((byte) 0))).andReturn(null);673 AndroidMock.expect(mockMap.get(AndroidMock.eq((short) 0))).andReturn(null);674 AndroidMock.expect(mockMap.get(AndroidMock.eq(0))).andReturn(null);675 AndroidMock.expect(mockMap.get(AndroidMock.eq(0L))).andReturn(null);676 AndroidMock.expect(mockMap.get(AndroidMock.eq(0.0))).andReturn(null);677 AndroidMock.expect(mockMap.get(AndroidMock.eq(0.0f))).andReturn(null);678 AndroidMock.expect(mockMap.get(AndroidMock.eq(0.0, 0.1))).andReturn(null);679 AndroidMock.expect(mockMap.get(AndroidMock.eq(0.0f, 0.1f))).andReturn(null);680 AndroidMock.expect(mockMap.get(AndroidMock.eq("hi"))).andReturn(null);681 AndroidMock.expect(mockMap.get(AndroidMock.eq('a'))).andReturn(null);682 AndroidMock.replay(mockMap);683 }684 public void testAryEq() {685 Map<?, ?> mockMap = AndroidMock.createMock(Map.class);686 AndroidMock.expect(mockMap.get(AndroidMock.aryEq(new boolean[] {true}))).andReturn(null);687 AndroidMock.expect(mockMap.get(AndroidMock.aryEq(new byte[] {(byte) 0}))).andReturn(null);688 AndroidMock.expect(mockMap.get(AndroidMock.aryEq(new short[] {(short) 0}))).andReturn(null);689 AndroidMock.expect(mockMap.get(AndroidMock.aryEq(new int[] {0}))).andReturn(null);690 AndroidMock.expect(mockMap.get(AndroidMock.aryEq(new long[] {0L}))).andReturn(null);691 AndroidMock.expect(mockMap.get(AndroidMock.aryEq(new double[] {0.0}))).andReturn(null);692 AndroidMock.expect(mockMap.get(AndroidMock.aryEq(new float[] {0.0f}))).andReturn(null);693 AndroidMock.expect(mockMap.get(AndroidMock.aryEq(new String[] {"hi"}))).andReturn(null);694 AndroidMock.expect(mockMap.get(AndroidMock.aryEq(new char[] {'a'}))).andReturn(null);695 AndroidMock.replay(mockMap);696 }697 public void testIsNull() {698 Map<?, ?> mockMap = AndroidMock.createMock(Map.class);699 AndroidMock.expect(mockMap.get(AndroidMock.isNull())).andReturn(null);700 AndroidMock.replay(mockMap);701 }702 public void testNotNull() {703 Map<?, ?> mockMap = AndroidMock.createMock(Map.class);704 AndroidMock.expect(mockMap.get(AndroidMock.notNull())).andReturn(null);705 AndroidMock.replay(mockMap);706 }707 public void testFind() {708 Map<?, ?> mockMap = AndroidMock.createMock(Map.class);709 AndroidMock.expect(mockMap.get(AndroidMock.find("hi"))).andReturn(null);710 AndroidMock.replay(mockMap);711 }712 public void testMatches() {713 Map<?, ?> mockMap = AndroidMock.createMock(Map.class);714 AndroidMock.expect(mockMap.get(AndroidMock.matches("hi"))).andReturn(null);715 AndroidMock.replay(mockMap);716 }717 public void testStartsWith() {718 Map<?, ?> mockMap = AndroidMock.createMock(Map.class);719 AndroidMock.expect(mockMap.get(AndroidMock.startsWith("hi"))).andReturn(null);720 AndroidMock.replay(mockMap);721 }722 public void testEndsWith() {723 Map<?, ?> mockMap = AndroidMock.createMock(Map.class);724 AndroidMock.expect(mockMap.get(AndroidMock.endsWith("hi"))).andReturn(null);725 AndroidMock.replay(mockMap);726 }727 public void testSame() {728 Map<?, ?> mockMap = AndroidMock.createMock(Map.class);729 AndroidMock.expect(mockMap.get(AndroidMock.same("hi"))).andReturn(null);730 AndroidMock.replay(mockMap);731 }732 public void testCmpEq() {733 Map<?, ?> mockMap = AndroidMock.createMock(Map.class);734 AndroidMock.expect(mockMap.get(AndroidMock.cmpEq("hi"))).andReturn(null);735 AndroidMock.replay(mockMap);736 }737 public void testCmp() {738 Map<?, ?> mockMap = AndroidMock.createMock(Map.class);739 AndroidMock.expect(740 mockMap.get(AndroidMock.cmp("hi", String.CASE_INSENSITIVE_ORDER, LogicalOperator.EQUAL)))741 .andReturn(null);742 AndroidMock.replay(mockMap);743 }744 public void testCapture() {745 Map<?, ?> mockMap = AndroidMock.createMock(Map.class);746 AndroidMock.expect(mockMap.get(AndroidMock.capture(new Capture<Byte>()))).andReturn(null);747 AndroidMock.expect(mockMap.get(AndroidMock.capture(new Capture<Character>()))).andReturn(null);748 AndroidMock.expect(mockMap.get(AndroidMock.capture(new Capture<Double>()))).andReturn(null);749 AndroidMock.expect(mockMap.get(AndroidMock.capture(new Capture<Float>()))).andReturn(null);750 AndroidMock.expect(mockMap.get(AndroidMock.capture(new Capture<Integer>()))).andReturn(null);751 AndroidMock.expect(mockMap.get(AndroidMock.capture(new Capture<Long>()))).andReturn(null);752 AndroidMock.expect(mockMap.get(AndroidMock.capture(new Capture<String>()))).andReturn(null);753 AndroidMock.replay(mockMap);754 }755 public void testReportMatcher() {756 Map<?, ?> mockMap = AndroidMock.createMock(Map.class);757 AndroidMock.reportMatcher(new Equals(null));758 AndroidMock.expect(mockMap.get(null)).andReturn(null);759 AndroidMock.replay(mockMap);760 }761 public void testGetCurrentArguments() {762 Map<?, ?> mockMap = AndroidMock.createMock(Map.class);763 AndroidMock.expect(mockMap.get(null)).andAnswer(new IAnswer() {764 @Override765 public Object answer() {766 AndroidMock.getCurrentArguments();767 return null;768 }769 });770 AndroidMock.replay(mockMap);771 mockMap.get(null);772 }773 public void testMakeThreadSafe() {774 Map<?, ?> mockMap = AndroidMock.createMock(Map.class);775 AndroidMock.makeThreadSafe(mockMap, false);776 AndroidMock.replay(mockMap);777 }778 public void testAndThrowsOnMockedInterface() throws IOException {779 ObjectInput mockInStream = AndroidMock.createMock(ObjectInput.class);780 AndroidMock.expect(mockInStream.read()).andThrow(new IOException("foo"));781 AndroidMock.replay(mockInStream);782 try {783 mockInStream.read();784 fail("IOException not thrown");785 } catch (IOException e) {786 assertEquals("foo", e.getMessage());787 }788 AndroidMock.verify(mockInStream);789 }790 public void testAndThrowsOnMockedClass() throws IOException, ClassNotFoundException,791 CannotCompileException, NotFoundException {792 List<GeneratedClassFile> mockClasses =793 new AndroidMockGenerator().createMocksForClass(InputStream.class);794 compileClasses(mockClasses);795 InputStream mockInStream = AndroidMock.createMock(InputStream.class);796 AndroidMock.expect(mockInStream.read()).andThrow(new IOException("foo"));797 AndroidMock.replay(mockInStream);798 try {799 mockInStream.read();800 fail("IOException not thrown");801 } catch (IOException e) {802 assertEquals("foo", e.getMessage());803 }804 AndroidMock.verify(mockInStream);805 }806 /**807 * Used for testing that a given method on Android Mock calls the equivalent808 * method on EasyMock, to ensure that the method-wiring of Android Mock is809 * correct.810 * 811 * @author swoodward@google.com (Stephen Woodward)812 */813 class MethodVerifier extends ExprEditor {814 private CtMethod expectedMethod;815 private boolean methodCalled;816 MethodVerifier(CtMethod expectedMethod) {817 this.expectedMethod = expectedMethod;818 }...
MockObjectTest.php
Source:MockObjectTest.php
1<?php2/*3 * This file is part of the phpunit-mock-objects package.4 *5 * (c) Sebastian Bergmann <sebastian@phpunit.de>6 *7 * For the full copyright and license information, please view the LICENSE8 * file that was distributed with this source code.9 */10use PHPUnit\Framework\MockObject\MockObject;11use PHPUnit\Framework\TestCase;12use PHPUnit\Framework\ExpectationFailedException;13class MockObjectTest extends TestCase14{15 public function testMockedMethodIsNeverCalled()16 {17 $mock = $this->getMockBuilder(AnInterface::class)18 ->getMock();19 $mock->expects($this->never())20 ->method('doSomething');21 }22 public function testMockedMethodIsNeverCalledWithParameter()23 {24 $mock = $this->getMockBuilder(SomeClass::class)25 ->getMock();26 $mock->expects($this->never())27 ->method('doSomething')28 ->with('someArg');29 }30 /**31 * @doesNotPerformAssertions32 */33 public function testMockedMethodIsNotCalledWhenExpectsAnyWithParameter()34 {35 $mock = $this->getMockBuilder(SomeClass::class)36 ->getMock();37 $mock->expects($this->any())38 ->method('doSomethingElse')39 ->with('someArg');40 }41 /**42 * @doesNotPerformAssertions43 */44 public function testMockedMethodIsNotCalledWhenMethodSpecifiedDirectlyWithParameter()45 {46 $mock = $this->getMockBuilder(SomeClass::class)47 ->getMock();48 $mock->method('doSomethingElse')49 ->with('someArg');50 }51 public function testMockedMethodIsCalledAtLeastOnce()52 {53 $mock = $this->getMockBuilder(AnInterface::class)54 ->getMock();55 $mock->expects($this->atLeastOnce())56 ->method('doSomething');57 $mock->doSomething();58 }59 public function testMockedMethodIsCalledAtLeastOnce2()60 {61 $mock = $this->getMockBuilder(AnInterface::class)62 ->getMock();63 $mock->expects($this->atLeastOnce())64 ->method('doSomething');65 $mock->doSomething();66 $mock->doSomething();67 }68 public function testMockedMethodIsCalledAtLeastTwice()69 {70 $mock = $this->getMockBuilder(AnInterface::class)71 ->getMock();72 $mock->expects($this->atLeast(2))73 ->method('doSomething');74 $mock->doSomething();75 $mock->doSomething();76 }77 public function testMockedMethodIsCalledAtLeastTwice2()78 {79 $mock = $this->getMockBuilder(AnInterface::class)80 ->getMock();81 $mock->expects($this->atLeast(2))82 ->method('doSomething');83 $mock->doSomething();84 $mock->doSomething();85 $mock->doSomething();86 }87 public function testMockedMethodIsCalledAtMostTwice()88 {89 $mock = $this->getMockBuilder(AnInterface::class)90 ->getMock();91 $mock->expects($this->atMost(2))92 ->method('doSomething');93 $mock->doSomething();94 $mock->doSomething();95 }96 public function testMockedMethodIsCalledAtMosttTwice2()97 {98 $mock = $this->getMockBuilder(AnInterface::class)99 ->getMock();100 $mock->expects($this->atMost(2))101 ->method('doSomething');102 $mock->doSomething();103 }104 public function testMockedMethodIsCalledOnce()105 {106 $mock = $this->getMockBuilder(AnInterface::class)107 ->getMock();108 $mock->expects($this->once())109 ->method('doSomething');110 $mock->doSomething();111 }112 public function testMockedMethodIsCalledOnceWithParameter()113 {114 $mock = $this->getMockBuilder(SomeClass::class)115 ->getMock();116 $mock->expects($this->once())117 ->method('doSomethingElse')118 ->with($this->equalTo('something'));119 $mock->doSomethingElse('something');120 }121 public function testMockedMethodIsCalledExactly()122 {123 $mock = $this->getMockBuilder(AnInterface::class)124 ->getMock();125 $mock->expects($this->exactly(2))126 ->method('doSomething');127 $mock->doSomething();128 $mock->doSomething();129 }130 public function testStubbedException()131 {132 $mock = $this->getMockBuilder(AnInterface::class)133 ->getMock();134 $mock->expects($this->any())135 ->method('doSomething')136 ->will($this->throwException(new \Exception()));137 $this->expectException(\Exception::class);138 $mock->doSomething();139 }140 public function testStubbedWillThrowException()141 {142 $mock = $this->getMockBuilder(AnInterface::class)143 ->getMock();144 $mock->expects($this->any())145 ->method('doSomething')146 ->willThrowException(new \Exception());147 $this->expectException(\Exception::class);148 $mock->doSomething();149 }150 public function testStubbedReturnValue()151 {152 $mock = $this->getMockBuilder(AnInterface::class)153 ->getMock();154 $mock->expects($this->any())155 ->method('doSomething')156 ->will($this->returnValue('something'));157 $this->assertEquals('something', $mock->doSomething());158 $mock = $this->getMockBuilder(AnInterface::class)159 ->getMock();160 $mock->expects($this->any())161 ->method('doSomething')162 ->willReturn('something');163 $this->assertEquals('something', $mock->doSomething());164 }165 public function testStubbedReturnValueMap()166 {167 $map = [168 ['a', 'b', 'c', 'd'],169 ['e', 'f', 'g', 'h']170 ];171 $mock = $this->getMockBuilder(AnInterface::class)172 ->getMock();173 $mock->expects($this->any())174 ->method('doSomething')175 ->will($this->returnValueMap($map));176 $this->assertEquals('d', $mock->doSomething('a', 'b', 'c'));177 $this->assertEquals('h', $mock->doSomething('e', 'f', 'g'));178 $this->assertEquals(null, $mock->doSomething('foo', 'bar'));179 $mock = $this->getMockBuilder(AnInterface::class)180 ->getMock();181 $mock->expects($this->any())182 ->method('doSomething')183 ->willReturnMap($map);184 $this->assertEquals('d', $mock->doSomething('a', 'b', 'c'));185 $this->assertEquals('h', $mock->doSomething('e', 'f', 'g'));186 $this->assertEquals(null, $mock->doSomething('foo', 'bar'));187 }188 public function testStubbedReturnArgument()189 {190 $mock = $this->getMockBuilder(AnInterface::class)191 ->getMock();192 $mock->expects($this->any())193 ->method('doSomething')194 ->will($this->returnArgument(1));195 $this->assertEquals('b', $mock->doSomething('a', 'b'));196 $mock = $this->getMockBuilder(AnInterface::class)197 ->getMock();198 $mock->expects($this->any())199 ->method('doSomething')200 ->willReturnArgument(1);201 $this->assertEquals('b', $mock->doSomething('a', 'b'));202 }203 public function testFunctionCallback()204 {205 $mock = $this->getMockBuilder(SomeClass::class)206 ->setMethods(['doSomething'])207 ->getMock();208 $mock->expects($this->once())209 ->method('doSomething')210 ->will($this->returnCallback('functionCallback'));211 $this->assertEquals('pass', $mock->doSomething('foo', 'bar'));212 $mock = $this->getMockBuilder(SomeClass::class)213 ->setMethods(['doSomething'])214 ->getMock();215 $mock->expects($this->once())216 ->method('doSomething')217 ->willReturnCallback('functionCallback');218 $this->assertEquals('pass', $mock->doSomething('foo', 'bar'));219 }220 public function testStubbedReturnSelf()221 {222 $mock = $this->getMockBuilder(AnInterface::class)223 ->getMock();224 $mock->expects($this->any())225 ->method('doSomething')226 ->will($this->returnSelf());227 $this->assertEquals($mock, $mock->doSomething());228 $mock = $this->getMockBuilder(AnInterface::class)229 ->getMock();230 $mock->expects($this->any())231 ->method('doSomething')232 ->willReturnSelf();233 $this->assertEquals($mock, $mock->doSomething());234 }235 public function testStubbedReturnOnConsecutiveCalls()236 {237 $mock = $this->getMockBuilder(AnInterface::class)238 ->getMock();239 $mock->expects($this->any())240 ->method('doSomething')241 ->will($this->onConsecutiveCalls('a', 'b', 'c'));242 $this->assertEquals('a', $mock->doSomething());243 $this->assertEquals('b', $mock->doSomething());244 $this->assertEquals('c', $mock->doSomething());245 $mock = $this->getMockBuilder(AnInterface::class)246 ->getMock();247 $mock->expects($this->any())248 ->method('doSomething')249 ->willReturnOnConsecutiveCalls('a', 'b', 'c');250 $this->assertEquals('a', $mock->doSomething());251 $this->assertEquals('b', $mock->doSomething());252 $this->assertEquals('c', $mock->doSomething());253 }254 public function testStaticMethodCallback()255 {256 $mock = $this->getMockBuilder(SomeClass::class)257 ->setMethods(['doSomething'])258 ->getMock();259 $mock->expects($this->once())260 ->method('doSomething')261 ->will($this->returnCallback(['MethodCallback', 'staticCallback']));262 $this->assertEquals('pass', $mock->doSomething('foo', 'bar'));263 }264 public function testPublicMethodCallback()265 {266 $mock = $this->getMockBuilder(SomeClass::class)267 ->setMethods(['doSomething'])268 ->getMock();269 $mock->expects($this->once())270 ->method('doSomething')271 ->will($this->returnCallback([new MethodCallback, 'nonStaticCallback']));272 $this->assertEquals('pass', $mock->doSomething('foo', 'bar'));273 }274 public function testMockClassOnlyGeneratedOnce()275 {276 $mock1 = $this->getMockBuilder(AnInterface::class)277 ->getMock();278 $mock2 = $this->getMockBuilder(AnInterface::class)279 ->getMock();280 $this->assertEquals(get_class($mock1), get_class($mock2));281 }282 public function testMockClassDifferentForPartialMocks()283 {284 $mock1 = $this->getMockBuilder(PartialMockTestClass::class)285 ->getMock();286 $mock2 = $this->getMockBuilder(PartialMockTestClass::class)287 ->setMethods(['doSomething'])288 ->getMock();289 $mock3 = $this->getMockBuilder(PartialMockTestClass::class)290 ->setMethods(['doSomething'])291 ->getMock();292 $mock4 = $this->getMockBuilder(PartialMockTestClass::class)293 ->setMethods(['doAnotherThing'])294 ->getMock();295 $mock5 = $this->getMockBuilder(PartialMockTestClass::class)296 ->setMethods(['doAnotherThing'])297 ->getMock();298 $this->assertNotEquals(get_class($mock1), get_class($mock2));299 $this->assertNotEquals(get_class($mock1), get_class($mock3));300 $this->assertNotEquals(get_class($mock1), get_class($mock4));301 $this->assertNotEquals(get_class($mock1), get_class($mock5));302 $this->assertEquals(get_class($mock2), get_class($mock3));303 $this->assertNotEquals(get_class($mock2), get_class($mock4));304 $this->assertNotEquals(get_class($mock2), get_class($mock5));305 $this->assertEquals(get_class($mock4), get_class($mock5));306 }307 public function testMockClassStoreOverrulable()308 {309 $mock1 = $this->getMockBuilder(PartialMockTestClass::class)310 ->getMock();311 $mock2 = $this->getMockBuilder(PartialMockTestClass::class)312 ->setMockClassName('MyMockClassNameForPartialMockTestClass1')313 ->getMock();314 $mock3 = $this->getMockBuilder(PartialMockTestClass::class)315 ->getMock();316 $mock4 = $this->getMockBuilder(PartialMockTestClass::class)317 ->setMethods(['doSomething'])318 ->setMockClassName('AnotherMockClassNameForPartialMockTestClass')319 ->getMock();320 $mock5 = $this->getMockBuilder(PartialMockTestClass::class)321 ->setMockClassName('MyMockClassNameForPartialMockTestClass2')322 ->getMock();323 $this->assertNotEquals(get_class($mock1), get_class($mock2));324 $this->assertEquals(get_class($mock1), get_class($mock3));325 $this->assertNotEquals(get_class($mock1), get_class($mock4));326 $this->assertNotEquals(get_class($mock2), get_class($mock3));327 $this->assertNotEquals(get_class($mock2), get_class($mock4));328 $this->assertNotEquals(get_class($mock2), get_class($mock5));329 $this->assertNotEquals(get_class($mock3), get_class($mock4));330 $this->assertNotEquals(get_class($mock3), get_class($mock5));331 $this->assertNotEquals(get_class($mock4), get_class($mock5));332 }333 public function testGetMockWithFixedClassNameCanProduceTheSameMockTwice()334 {335 $mock = $this->getMockBuilder(stdClass::class)->setMockClassName('FixedName')->getMock();336 $mock = $this->getMockBuilder(stdClass::class)->setMockClassName('FixedName')->getMock();337 $this->assertInstanceOf(stdClass::class, $mock);338 }339 public function testOriginalConstructorSettingConsidered()340 {341 $mock1 = $this->getMockBuilder(PartialMockTestClass::class)342 ->getMock();343 $mock2 = $this->getMockBuilder(PartialMockTestClass::class)344 ->disableOriginalConstructor()345 ->getMock();346 $this->assertTrue($mock1->constructorCalled);347 $this->assertFalse($mock2->constructorCalled);348 }349 public function testOriginalCloneSettingConsidered()350 {351 $mock1 = $this->getMockBuilder(PartialMockTestClass::class)352 ->getMock();353 $mock2 = $this->getMockBuilder(PartialMockTestClass::class)354 ->disableOriginalClone()355 ->getMock();356 $this->assertNotEquals(get_class($mock1), get_class($mock2));357 }358 public function testGetMockForAbstractClass()359 {360 $mock = $this->getMockBuilder(AbstractMockTestClass::class)361 ->getMock();362 $mock->expects($this->never())363 ->method('doSomething');364 }365 /**366 * @dataProvider traversableProvider367 */368 public function testGetMockForTraversable($type)369 {370 $mock = $this->getMockBuilder($type)371 ->getMock();372 $this->assertInstanceOf(Traversable::class, $mock);373 }374 public function testMultipleInterfacesCanBeMockedInSingleObject()375 {376 $mock = $this->getMockBuilder([AnInterface::class, AnotherInterface::class])377 ->getMock();378 $this->assertInstanceOf(AnInterface::class, $mock);379 $this->assertInstanceOf(AnotherInterface::class, $mock);380 }381 public function testGetMockForTrait()382 {383 $mock = $this->getMockForTrait(AbstractTrait::class);384 $mock->expects($this->never())385 ->method('doSomething');386 $parent = get_parent_class($mock);387 $traits = class_uses($parent, false);388 $this->assertContains(AbstractTrait::class, $traits);389 }390 public function testClonedMockObjectShouldStillEqualTheOriginal()391 {392 $a = $this->getMockBuilder(stdClass::class)393 ->getMock();394 $b = clone $a;395 $this->assertEquals($a, $b);396 }397 public function testMockObjectsConstructedIndepentantlyShouldBeEqual()398 {399 $a = $this->getMockBuilder(stdClass::class)400 ->getMock();401 $b = $this->getMockBuilder(stdClass::class)402 ->getMock();403 $this->assertEquals($a, $b);404 }405 public function testMockObjectsConstructedIndepentantlyShouldNotBeTheSame()406 {407 $a = $this->getMockBuilder(stdClass::class)408 ->getMock();409 $b = $this->getMockBuilder(stdClass::class)410 ->getMock();411 $this->assertNotSame($a, $b);412 }413 public function testClonedMockObjectCanBeUsedInPlaceOfOriginalOne()414 {415 $x = $this->getMockBuilder(stdClass::class)416 ->getMock();417 $y = clone $x;418 $mock = $this->getMockBuilder(stdClass::class)419 ->setMethods(['foo'])420 ->getMock();421 $mock->expects($this->once())422 ->method('foo')423 ->with($this->equalTo($x));424 $mock->foo($y);425 }426 public function testClonedMockObjectIsNotIdenticalToOriginalOne()427 {428 $x = $this->getMockBuilder(stdClass::class)429 ->getMock();430 $y = clone $x;431 $mock = $this->getMockBuilder(stdClass::class)432 ->setMethods(['foo'])433 ->getMock();434 $mock->expects($this->once())435 ->method('foo')436 ->with($this->logicalNot($this->identicalTo($x)));437 $mock->foo($y);438 }439 public function testObjectMethodCallWithArgumentCloningEnabled()440 {441 $expectedObject = new stdClass;442 $mock = $this->getMockBuilder('SomeClass')443 ->setMethods(['doSomethingElse'])444 ->enableArgumentCloning()445 ->getMock();446 $actualArguments = [];447 $mock->expects($this->any())448 ->method('doSomethingElse')449 ->will(450 $this->returnCallback(451 function () use (&$actualArguments) {452 $actualArguments = func_get_args();453 }454 )455 );456 $mock->doSomethingElse($expectedObject);457 $this->assertEquals(1, count($actualArguments));458 $this->assertEquals($expectedObject, $actualArguments[0]);459 $this->assertNotSame($expectedObject, $actualArguments[0]);460 }461 public function testObjectMethodCallWithArgumentCloningDisabled()462 {463 $expectedObject = new stdClass;464 $mock = $this->getMockBuilder('SomeClass')465 ->setMethods(['doSomethingElse'])466 ->disableArgumentCloning()467 ->getMock();468 $actualArguments = [];469 $mock->expects($this->any())470 ->method('doSomethingElse')471 ->will(472 $this->returnCallback(473 function () use (&$actualArguments) {474 $actualArguments = func_get_args();475 }476 )477 );478 $mock->doSomethingElse($expectedObject);479 $this->assertEquals(1, count($actualArguments));480 $this->assertSame($expectedObject, $actualArguments[0]);481 }482 public function testArgumentCloningOptionGeneratesUniqueMock()483 {484 $mockWithCloning = $this->getMockBuilder('SomeClass')485 ->setMethods(['doSomethingElse'])486 ->enableArgumentCloning()487 ->getMock();488 $mockWithoutCloning = $this->getMockBuilder('SomeClass')489 ->setMethods(['doSomethingElse'])490 ->disableArgumentCloning()491 ->getMock();492 $this->assertNotEquals($mockWithCloning, $mockWithoutCloning);493 }494 public function testVerificationOfMethodNameFailsWithoutParameters()495 {496 $mock = $this->getMockBuilder(SomeClass::class)497 ->setMethods(['right', 'wrong'])498 ->getMock();499 $mock->expects($this->once())500 ->method('right');501 $mock->wrong();502 try {503 $mock->__phpunit_verify();504 $this->fail('Expected exception');505 } catch (ExpectationFailedException $e) {506 $this->assertSame(507 'Expectation failed for method name is equal to "right" when invoked 1 time(s).' . PHP_EOL .508 'Method was expected to be called 1 times, actually called 0 times.' . PHP_EOL,509 $e->getMessage()510 );511 }512 $this->resetMockObjects();513 }514 public function testVerificationOfMethodNameFailsWithParameters()515 {516 $mock = $this->getMockBuilder(SomeClass::class)517 ->setMethods(['right', 'wrong'])518 ->getMock();519 $mock->expects($this->once())520 ->method('right');521 $mock->wrong();522 try {523 $mock->__phpunit_verify();524 $this->fail('Expected exception');525 } catch (ExpectationFailedException $e) {526 $this->assertSame(527 'Expectation failed for method name is equal to "right" when invoked 1 time(s).' . PHP_EOL .528 'Method was expected to be called 1 times, actually called 0 times.' . PHP_EOL,529 $e->getMessage()530 );531 }532 $this->resetMockObjects();533 }534 public function testVerificationOfMethodNameFailsWithWrongParameters()535 {536 $mock = $this->getMockBuilder(SomeClass::class)537 ->setMethods(['right', 'wrong'])538 ->getMock();539 $mock->expects($this->once())540 ->method('right')541 ->with(['first', 'second']);542 try {543 $mock->right(['second']);544 } catch (ExpectationFailedException $e) {545 $this->assertSame(546 'Expectation failed for method name is equal to "right" when invoked 1 time(s)' . PHP_EOL .547 'Parameter 0 for invocation SomeClass::right(Array (...)) does not match expected value.' . PHP_EOL .548 'Failed asserting that two arrays are equal.',549 $e->getMessage()550 );551 }552 try {553 $mock->__phpunit_verify();554// CHECKOUT THIS MORE CAREFULLY555// $this->fail('Expected exception');556 } catch (ExpectationFailedException $e) {557 $this->assertSame(558 'Expectation failed for method name is equal to "right" when invoked 1 time(s).' . PHP_EOL .559 'Parameter 0 for invocation SomeClass::right(Array (...)) does not match expected value.' . PHP_EOL .560 'Failed asserting that two arrays are equal.' . PHP_EOL .561 '--- Expected' . PHP_EOL .562 '+++ Actual' . PHP_EOL .563 '@@ @@' . PHP_EOL .564 ' Array (' . PHP_EOL .565 '- 0 => \'first\'' . PHP_EOL .566 '- 1 => \'second\'' . PHP_EOL .567 '+ 0 => \'second\'' . PHP_EOL,568 $e->getMessage()569 );570 }571 $this->resetMockObjects();572 }573 public function testVerificationOfNeverFailsWithEmptyParameters()574 {575 $mock = $this->getMockBuilder(SomeClass::class)576 ->setMethods(['right', 'wrong'])577 ->getMock();578 $mock->expects($this->never())579 ->method('right')580 ->with();581 try {582 $mock->right();583 $this->fail('Expected exception');584 } catch (ExpectationFailedException $e) {585 $this->assertSame(586 'SomeClass::right() was not expected to be called.',587 $e->getMessage()588 );589 }590 $this->resetMockObjects();591 }592 public function testVerificationOfNeverFailsWithAnyParameters()593 {594 $mock = $this->getMockBuilder(SomeClass::class)595 ->setMethods(['right', 'wrong'])596 ->getMock();597 $mock->expects($this->never())598 ->method('right')599 ->withAnyParameters();600 try {601 $mock->right();602 $this->fail('Expected exception');603 } catch (ExpectationFailedException $e) {604 $this->assertSame(605 'SomeClass::right() was not expected to be called.',606 $e->getMessage()607 );608 }609 $this->resetMockObjects();610 }611 public function testWithAnythingInsteadOfWithAnyParameters()612 {613 $mock = $this->getMockBuilder(SomeClass::class)614 ->setMethods(['right', 'wrong'])615 ->getMock();616 $mock->expects($this->once())617 ->method('right')618 ->with($this->anything());619 try {620 $mock->right();621 $this->fail('Expected exception');622 } catch (ExpectationFailedException $e) {623 $this->assertSame(624 'Expectation failed for method name is equal to "right" when invoked 1 time(s)' . PHP_EOL .625 'Parameter count for invocation SomeClass::right() is too low.' . PHP_EOL .626 'To allow 0 or more parameters with any value, omit ->with() or use ->withAnyParameters() instead.',627 $e->getMessage()628 );629 }630 $this->resetMockObjects();631 }632 /**633 * See https://github.com/sebastianbergmann/phpunit-mock-objects/issues/81634 */635 public function testMockArgumentsPassedByReference()636 {637 $foo = $this->getMockBuilder('MethodCallbackByReference')638 ->setMethods(['bar'])639 ->disableOriginalConstructor()640 ->disableArgumentCloning()641 ->getMock();642 $foo->expects($this->any())643 ->method('bar')644 ->will($this->returnCallback([$foo, 'callback']));645 $a = $b = $c = 0;646 $foo->bar($a, $b, $c);647 $this->assertEquals(1, $b);648 }649 /**650 * See https://github.com/sebastianbergmann/phpunit-mock-objects/issues/81651 */652 public function testMockArgumentsPassedByReference2()653 {654 $foo = $this->getMockBuilder('MethodCallbackByReference')655 ->disableOriginalConstructor()656 ->disableArgumentCloning()657 ->getMock();658 $foo->expects($this->any())659 ->method('bar')660 ->will($this->returnCallback(661 function (&$a, &$b, $c) {662 $b = 1;663 }664 ));665 $a = $b = $c = 0;666 $foo->bar($a, $b, $c);667 $this->assertEquals(1, $b);668 }669 /**670 * @see https://github.com/sebastianbergmann/phpunit-mock-objects/issues/116671 */672 public function testMockArgumentsPassedByReference3()673 {674 $foo = $this->getMockBuilder('MethodCallbackByReference')675 ->setMethods(['bar'])676 ->disableOriginalConstructor()677 ->disableArgumentCloning()678 ->getMock();679 $a = new stdClass;680 $b = $c = 0;681 $foo->expects($this->any())682 ->method('bar')683 ->with($a, $b, $c)684 ->will($this->returnCallback([$foo, 'callback']));685 $this->assertNull($foo->bar($a, $b, $c));686 }687 /**688 * @see https://github.com/sebastianbergmann/phpunit/issues/796689 */690 public function testMockArgumentsPassedByReference4()691 {692 $foo = $this->getMockBuilder('MethodCallbackByReference')693 ->setMethods(['bar'])694 ->disableOriginalConstructor()695 ->disableArgumentCloning()696 ->getMock();697 $a = new stdClass;698 $b = $c = 0;699 $foo->expects($this->any())700 ->method('bar')701 ->with($this->isInstanceOf(stdClass::class), $b, $c)702 ->will($this->returnCallback([$foo, 'callback']));703 $this->assertNull($foo->bar($a, $b, $c));704 }705 /**706 * @requires extension soap707 */708 public function testCreateMockFromWsdl()709 {710 $mock = $this->getMockFromWsdl(__DIR__ . '/_fixture/GoogleSearch.wsdl', 'WsdlMock');711 $this->assertStringStartsWith(712 'Mock_WsdlMock_',713 get_class($mock)714 );715 }716 /**717 * @requires extension soap718 */719 public function testCreateNamespacedMockFromWsdl()720 {721 $mock = $this->getMockFromWsdl(__DIR__ . '/_fixture/GoogleSearch.wsdl', 'My\\Space\\WsdlMock');722 $this->assertStringStartsWith(723 'Mock_WsdlMock_',724 get_class($mock)725 );726 }727 /**728 * @requires extension soap729 */730 public function testCreateTwoMocksOfOneWsdlFile()731 {732 $a = $this->getMockFromWsdl(__DIR__ . '/_fixture/GoogleSearch.wsdl');733 $b = $this->getMockFromWsdl(__DIR__ . '/_fixture/GoogleSearch.wsdl');734 $this->assertStringStartsWith('Mock_GoogleSearch_', get_class($a));735 $this->assertEquals(get_class($a), get_class($b));736 }737 /**738 * @see https://github.com/sebastianbergmann/phpunit-mock-objects/issues/156739 * @ticket 156740 */741 public function testInterfaceWithStaticMethodCanBeStubbed()742 {743 $this->assertInstanceOf(744 InterfaceWithStaticMethod::class,745 $this->getMockBuilder(InterfaceWithStaticMethod::class)->getMock()746 );747 }748 public function testInvokingStubbedStaticMethodRaisesException()749 {750 $mock = $this->getMockBuilder(ClassWithStaticMethod::class)->getMock();751 $this->expectException(\PHPUnit\Framework\MockObject\BadMethodCallException::class);752 $mock->staticMethod();753 }754 /**755 * @see https://github.com/sebastianbergmann/phpunit-mock-objects/issues/171756 * @ticket 171757 */758 public function testStubForClassThatImplementsSerializableCanBeCreatedWithoutInvokingTheConstructor()759 {760 $this->assertInstanceOf(761 ClassThatImplementsSerializable::class,762 $this->getMockBuilder(ClassThatImplementsSerializable::class)763 ->disableOriginalConstructor()764 ->getMock()765 );766 }767 public function testGetMockForClassWithSelfTypeHint()768 {769 $this->assertInstanceOf(770 ClassWithSelfTypeHint::class,771 $this->getMockBuilder(ClassWithSelfTypeHint::class)->getMock()772 );773 }774 private function resetMockObjects()775 {776 $refl = new ReflectionObject($this);777 $refl = $refl->getParentClass();778 $prop = $refl->getProperty('mockObjects');779 $prop->setAccessible(true);780 $prop->setValue($this, []);781 }782 public function testStringableClassDoesNotThrow()783 {784 $mock = $this->getMockBuilder(StringableClass::class)->getMock();785 $this->assertInternalType('string', (string) $mock);786 }787 public function testStringableClassCanBeMocked()788 {789 $mock = $this->getMockBuilder(StringableClass::class)->getMock();790 $mock->method('__toString')->willReturn('foo');791 $this->assertSame('foo', (string) $mock);792 }793 public function traversableProvider()794 {795 return [796 ['Traversable'],797 ['\Traversable'],798 ['TraversableMockTestInterface'],799 [['Traversable']],800 [['Iterator','Traversable']],801 [['\Iterator','\Traversable']]802 ];803 }804 public function testParameterCallbackConstraintOnlyEvaluatedOnce()805 {806 $mock = $this->getMockBuilder(Foo::class)->setMethods(['bar'])->getMock();807 $expectedNumberOfCalls = 1;808 $callCount = 0;809 $mock->expects($this->exactly($expectedNumberOfCalls))->method('bar')810 ->with($this->callback(function ($argument) use (&$callCount) {811 return $argument === 'call_' . $callCount++;812 }));813 for ($i = 0; $i < $expectedNumberOfCalls; $i++) {814 $mock->bar('call_' . $i);815 }816 }817 public function testReturnTypesAreMockedCorrectly()818 {819 /** @var ClassWithAllPossibleReturnTypes|MockObject $stub */820 $stub = $this->createMock(ClassWithAllPossibleReturnTypes::class);821 $this->assertNull($stub->methodWithNoReturnTypeDeclaration());822 $this->assertSame('', $stub->methodWithStringReturnTypeDeclaration());823 $this->assertSame(0.0, $stub->methodWithFloatReturnTypeDeclaration());824 $this->assertSame(0, $stub->methodWithIntReturnTypeDeclaration());825 $this->assertFalse($stub->methodWithBoolReturnTypeDeclaration());826 $this->assertSame([], $stub->methodWithArrayReturnTypeDeclaration());827 $this->assertInstanceOf(MockObject::class, $stub->methodWithClassReturnTypeDeclaration());828 }...
CipherTest.java
Source:CipherTest.java
...34 }35 public abstract void setup();36 }37 public void testCipher_getInstance_SuppliedProviderNotRegistered_Success() throws Exception {38 Provider mockProvider = new MockProvider("MockProvider") {39 public void setup() {40 put("Cipher.FOO", MockCipherSpi.AllKeyTypes.class.getName());41 }42 };43 {44 Cipher c = Cipher.getInstance("FOO", mockProvider);45 c.init(Cipher.ENCRYPT_MODE, new MockKey());46 assertEquals(mockProvider, c.getProvider());47 }48 }49 public void testCipher_getInstance_DoesNotSupportKeyClass_Success() throws Exception {50 Provider mockProvider = new MockProvider("MockProvider") {51 public void setup() {52 put("Cipher.FOO", MockCipherSpi.AllKeyTypes.class.getName());53 put("Cipher.FOO SupportedKeyClasses", "None");54 }55 };56 Security.addProvider(mockProvider);57 try {58 Cipher c = Cipher.getInstance("FOO", mockProvider);59 c.init(Cipher.ENCRYPT_MODE, new MockKey());60 assertEquals(mockProvider, c.getProvider());61 } finally {62 Security.removeProvider(mockProvider.getName());63 }64 }65 public void testCipher_getInstance_SuppliedProviderNotRegistered_MultipartTransform_Success()66 throws Exception {67 Provider mockProvider = new MockProvider("MockProvider") {68 public void setup() {69 put("Cipher.FOO", MockCipherSpi.AllKeyTypes.class.getName());70 }71 };72 {73 Cipher c = Cipher.getInstance("FOO/FOO/FOO", mockProvider);74 c.init(Cipher.ENCRYPT_MODE, new MockKey());75 assertEquals(mockProvider, c.getProvider());76 }77 }78 public void testCipher_getInstance_OnlyUsesSpecifiedProvider_SameNameAndClass_Success()79 throws Exception {80 Provider mockProvider = new MockProvider("MockProvider") {81 public void setup() {82 put("Cipher.FOO", MockCipherSpi.AllKeyTypes.class.getName());83 }84 };85 Security.addProvider(mockProvider);86 try {87 {88 Provider mockProvider2 = new MockProvider("MockProvider") {89 public void setup() {90 put("Cipher.FOO", MockCipherSpi.AllKeyTypes.class.getName());91 }92 };93 Cipher c = Cipher.getInstance("FOO", mockProvider2);94 assertEquals(mockProvider2, c.getProvider());95 }96 } finally {97 Security.removeProvider(mockProvider.getName());98 }99 }100 public void testCipher_getInstance_DelayedInitialization_KeyType() throws Exception {101 Provider mockProviderSpecific = new MockProvider("MockProviderSpecific") {102 public void setup() {103 put("Cipher.FOO", MockCipherSpi.SpecificKeyTypes.class.getName());104 put("Cipher.FOO SupportedKeyClasses", MockKey.class.getName());105 }106 };107 Provider mockProviderSpecific2 = new MockProvider("MockProviderSpecific2") {108 public void setup() {109 put("Cipher.FOO", MockCipherSpi.SpecificKeyTypes2.class.getName());110 put("Cipher.FOO SupportedKeyClasses", MockKey2.class.getName());111 }112 };113 Provider mockProviderAll = new MockProvider("MockProviderAll") {114 public void setup() {115 put("Cipher.FOO", MockCipherSpi.AllKeyTypes.class.getName());116 }117 };118 Security.addProvider(mockProviderSpecific);119 Security.addProvider(mockProviderSpecific2);120 Security.addProvider(mockProviderAll);121 try {122 {123 System.out.println(Arrays.deepToString(Security.getProviders("Cipher.FOO")));124 Cipher c = Cipher.getInstance("FOO");125 c.init(Cipher.ENCRYPT_MODE, new MockKey());126 assertEquals(mockProviderSpecific, c.getProvider());127 try {128 c.init(Cipher.ENCRYPT_MODE, new MockKey2());129 assertEquals(mockProviderSpecific2, c.getProvider());130 if (StandardNames.IS_RI) {131 fail("RI was broken before; fix tests now that it works!");132 }133 } catch (InvalidKeyException e) {134 if (!StandardNames.IS_RI) {135 fail("Non-RI should select the right provider");136 }137 }138 }139 {140 Cipher c = Cipher.getInstance("FOO");141 c.init(Cipher.ENCRYPT_MODE, new Key() {142 @Override143 public String getAlgorithm() {144 throw new UnsupportedOperationException("not implemented");145 }146 @Override147 public String getFormat() {148 throw new UnsupportedOperationException("not implemented");149 }150 @Override151 public byte[] getEncoded() {152 throw new UnsupportedOperationException("not implemented");153 }154 });155 assertEquals(mockProviderAll, c.getProvider());156 }157 {158 Cipher c = Cipher.getInstance("FOO");159 assertEquals(mockProviderSpecific, c.getProvider());160 }161 } finally {162 Security.removeProvider(mockProviderSpecific.getName());163 Security.removeProvider(mockProviderSpecific2.getName());164 Security.removeProvider(mockProviderAll.getName());165 }166 }167 public void testCipher_getInstance_CorrectPriority_AlgorithmOnlyFirst() throws Exception {168 Provider mockProviderOnlyAlgorithm = new MockProvider("MockProviderOnlyAlgorithm") {169 public void setup() {170 put("Cipher.FOO", MockCipherSpi.AllKeyTypes.class.getName());171 }172 };173 Provider mockProviderFullTransformSpecified = new MockProvider("MockProviderFull") {174 public void setup() {175 put("Cipher.FOO/FOO/FOO", MockCipherSpi.AllKeyTypes.class.getName());176 }177 };178 Security.addProvider(mockProviderOnlyAlgorithm);179 Security.addProvider(mockProviderFullTransformSpecified);180 try {181 Cipher c = Cipher.getInstance("FOO/FOO/FOO");182 assertEquals(mockProviderOnlyAlgorithm, c.getProvider());183 } finally {184 Security.removeProvider(mockProviderOnlyAlgorithm.getName());185 Security.removeProvider(mockProviderFullTransformSpecified.getName());186 }187 }188 public void testCipher_getInstance_CorrectPriority_FullTransformFirst() throws Exception {189 Provider mockProviderOnlyAlgorithm = new MockProvider("MockProviderOnlyAlgorithm") {190 public void setup() {191 put("Cipher.FOO", MockCipherSpi.AllKeyTypes.class.getName());192 }193 };194 Provider mockProviderFullTransformSpecified = new MockProvider("MockProviderFull") {195 public void setup() {196 put("Cipher.FOO/FOO/FOO", MockCipherSpi.AllKeyTypes.class.getName());197 }198 };199 Security.addProvider(mockProviderFullTransformSpecified);200 Security.addProvider(mockProviderOnlyAlgorithm);201 try {202 Cipher c = Cipher.getInstance("FOO/FOO/FOO");203 assertEquals(mockProviderFullTransformSpecified, c.getProvider());204 } finally {205 Security.removeProvider(mockProviderOnlyAlgorithm.getName());206 Security.removeProvider(mockProviderFullTransformSpecified.getName());207 }208 }209 public void testCipher_getInstance_CorrectPriority_AliasedAlgorithmFirst() throws Exception {210 Provider mockProviderAliasedAlgorithm = new MockProvider("MockProviderAliasedAlgorithm") {211 public void setup() {212 put("Cipher.BAR", MockCipherSpi.AllKeyTypes.class.getName());213 put("Alg.Alias.Cipher.FOO", "BAR");214 }215 };216 Provider mockProviderAlgorithmOnly = new MockProvider("MockProviderAlgorithmOnly") {217 public void setup() {218 put("Cipher.FOO", MockCipherSpi.AllKeyTypes.class.getName());219 }220 };221 Security.addProvider(mockProviderAliasedAlgorithm);222 Security.addProvider(mockProviderAlgorithmOnly);223 try {224 Cipher c = Cipher.getInstance("FOO/FOO/FOO");225 assertEquals(mockProviderAliasedAlgorithm, c.getProvider());226 } finally {227 Security.removeProvider(mockProviderAliasedAlgorithm.getName());228 Security.removeProvider(mockProviderAlgorithmOnly.getName());229 }230 }231 public void testCipher_getInstance_WrongType_Failure() throws Exception {232 Provider mockProviderInvalid = new MockProvider("MockProviderInvalid") {233 public void setup() {234 put("Cipher.FOO", Object.class.getName());235 }236 };237 Security.addProvider(mockProviderInvalid);238 try {239 Cipher c = Cipher.getInstance("FOO");240 c.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(new byte[16], "FOO"));241 fail("Should not find any matching providers; found: " + c);242 } catch (ClassCastException expected) {243 } finally {244 Security.removeProvider(mockProviderInvalid.getName());245 }246 }247 public void testCipher_init_CallsInitWithParams_AlgorithmParameterSpec() throws Exception {248 Provider mockProviderRejects = new MockProvider("MockProviderRejects") {249 public void setup() {250 put("Cipher.FOO",251 MockCipherSpi.MustInitWithAlgorithmParameterSpec_RejectsAll.class.getName());252 put("Cipher.FOO SupportedKeyClasses", MockKey.class.getName());253 }254 };255 Provider mockProviderAccepts = new MockProvider("MockProviderAccepts") {256 public void setup() {257 put("Cipher.FOO", MockCipherSpi.AllKeyTypes.class.getName());258 put("Cipher.FOO SupportedKeyClasses", MockKey.class.getName());259 }260 };261 Security.addProvider(mockProviderRejects);262 Security.addProvider(mockProviderAccepts);263 try {264 Cipher c = Cipher.getInstance("FOO");265 c.init(Cipher.ENCRYPT_MODE, new MockKey(), new IvParameterSpec(new byte[12]));266 assertEquals(mockProviderAccepts, c.getProvider());267 } finally {268 Security.removeProvider(mockProviderRejects.getName());269 Security.removeProvider(mockProviderAccepts.getName());270 }271 }272 public void testCipher_init_CallsInitWithParams_AlgorithmParameters() throws Exception {273 Provider mockProviderRejects = new MockProvider("MockProviderRejects") {274 public void setup() {275 put("Cipher.FOO",276 MockCipherSpi.MustInitWithAlgorithmParameters_RejectsAll.class.getName());277 put("Cipher.FOO SupportedKeyClasses", MockKey.class.getName());278 }279 };280 Provider mockProviderAccepts = new MockProvider("MockProviderAccepts") {281 public void setup() {282 put("Cipher.FOO", MockCipherSpi.AllKeyTypes.class.getName());283 put("Cipher.FOO SupportedKeyClasses", MockKey.class.getName());284 }285 };286 Security.addProvider(mockProviderRejects);287 Security.addProvider(mockProviderAccepts);288 try {289 Cipher c = Cipher.getInstance("FOO");290 c.init(Cipher.ENCRYPT_MODE, new MockKey(), AlgorithmParameters.getInstance("AES"));291 assertEquals(mockProviderAccepts, c.getProvider());292 } finally {293 Security.removeProvider(mockProviderRejects.getName());294 Security.removeProvider(mockProviderAccepts.getName());295 }296 }297 public void testCipher_init_CallsInitIgnoresRuntimeException() throws Exception {298 Provider mockProviderRejects = new MockProvider("MockProviderRejects") {299 public void setup() {300 put("Cipher.FOO",301 MockCipherSpi.MustInitWithAlgorithmParameters_ThrowsNull.class.getName());302 put("Cipher.FOO SupportedKeyClasses", MockKey.class.getName());303 }304 };305 Provider mockProviderAccepts = new MockProvider("MockProviderAccepts") {306 public void setup() {307 put("Cipher.FOO", MockCipherSpi.AllKeyTypes.class.getName());308 put("Cipher.FOO SupportedKeyClasses", MockKey.class.getName());309 }310 };311 Security.addProvider(mockProviderRejects);312 Security.addProvider(mockProviderAccepts);313 try {314 Cipher c = Cipher.getInstance("FOO");315 c.init(Cipher.ENCRYPT_MODE, new MockKey(), AlgorithmParameters.getInstance("AES"));316 assertEquals(mockProviderAccepts, c.getProvider());317 } finally {318 Security.removeProvider(mockProviderRejects.getName());319 Security.removeProvider(mockProviderAccepts.getName());320 }321 }322 public void testCipher_init_CallsInitWithMode() throws Exception {323 Provider mockProviderOnlyEncrypt = new MockProvider("MockProviderOnlyEncrypt") {324 public void setup() {325 put("Cipher.FOO", MockCipherSpi.MustInitForEncryptModeOrRejects.class.getName());326 put("Cipher.FOO SupportedKeyClasses", MockKey.class.getName());327 }328 };329 Provider mockProviderAcceptsAll = new MockProvider("MockProviderAcceptsAll") {330 public void setup() {331 put("Cipher.FOO", MockCipherSpi.AllKeyTypes.class.getName());332 put("Cipher.FOO SupportedKeyClasses", MockKey.class.getName());333 }334 };335 Security.addProvider(mockProviderOnlyEncrypt);336 Security.addProvider(mockProviderAcceptsAll);337 try {338 {339 Cipher c = Cipher.getInstance("FOO");340 c.init(Cipher.DECRYPT_MODE, new MockKey(), AlgorithmParameters.getInstance("AES"));341 assertEquals(mockProviderAcceptsAll, c.getProvider());342 }343 {344 Cipher c = Cipher.getInstance("FOO");345 c.init(Cipher.ENCRYPT_MODE, new MockKey(), AlgorithmParameters.getInstance("AES"));346 assertEquals(mockProviderOnlyEncrypt, c.getProvider());347 }348 } finally {349 Security.removeProvider(mockProviderOnlyEncrypt.getName());350 Security.removeProvider(mockProviderAcceptsAll.getName());351 }352 }353 /**354 * Several exceptions can be thrown by init. Check that in this case we throw the right one,355 * as the error could fall under the umbrella of other exceptions.356 * http://b/18987633357 */358 public void testCipher_init_DoesNotSupportKeyClass_throwsInvalidKeyException()359 throws Exception {360 Provider mockProvider = new MockProvider("MockProvider") {361 public void setup() {362 put("Cipher.FOO", MockCipherSpi.AllKeyTypes.class.getName());363 put("Cipher.FOO SupportedKeyClasses", "none");364 }365 };366 Security.addProvider(mockProvider);367 try {368 Cipher c = Cipher.getInstance("FOO");369 c.init(Cipher.DECRYPT_MODE, new MockKey());370 fail("Expected InvalidKeyException");371 } catch (InvalidKeyException expected) {372 } finally {373 Security.removeProvider(mockProvider.getName());374 }375 }376 /**377 * If a provider rejects a key for "Cipher/Mode/Padding"", there might be another that378 * accepts the key for "Cipher". Don't throw InvalidKeyException when trying the first one.379 * http://b/22208820380 */381 public void testCipher_init_tryAllCombinationsBeforeThrowingInvalidKey()382 throws Exception {383 Provider mockProvider = new MockProvider("MockProvider") {384 public void setup() {385 put("Cipher.FOO/FOO/FOO", MockCipherSpi.AllKeyTypes.class.getName());386 put("Cipher.FOO/FOO/FOO SupportedKeyClasses", "none");387 }388 };389 Provider mockProvider2 = new MockProvider("MockProvider2") {390 public void setup() {391 put("Cipher.FOO", MockCipherSpi.AllKeyTypes.class.getName());392 }393 };394 Security.addProvider(mockProvider);395 try {396 try {397 // The provider installed doesn't accept the key.398 Cipher c = Cipher.getInstance("FOO/FOO/FOO");399 c.init(Cipher.DECRYPT_MODE, new MockKey());400 fail("Expected InvalidKeyException");401 } catch (InvalidKeyException expected) {402 }403 Security.addProvider(mockProvider2);404 try {405 // The new provider accepts "FOO" with this key. Use it despite the other provider406 // accepts "FOO/FOO/FOO" but doesn't accept the key.407 Cipher c = Cipher.getInstance("FOO/FOO/FOO");408 c.init(Cipher.DECRYPT_MODE, new MockKey());409 assertEquals("MockProvider2", c.getProvider().getName());410 } finally {411 Security.removeProvider(mockProvider2.getName());412 }413 } finally {414 Security.removeProvider(mockProvider.getName());415 }416 }417 /**418 * http://b/29038928419 * If in a second call to init the current spi doesn't support the new specified key, look for420 * another suitable spi.421 */422 public void test_init_onKeyTypeChange_reInitCipher() throws Exception {423 Provider mockProvider = new MockProvider("MockProvider") {424 public void setup() {425 put("Cipher.FOO", MockCipherSpi.SpecificKeyTypes.class.getName());426 }427 };428 Provider mockProvider2 = new MockProvider("MockProvider2") {429 public void setup() {430 put("Cipher.FOO", MockCipherSpi.SpecificKeyTypes2.class.getName());431 }432 };433 try {434 Security.addProvider(mockProvider);435 Security.addProvider(mockProvider2);436 Cipher cipher = Cipher.getInstance("FOO");437 cipher.init(Cipher.ENCRYPT_MODE, new MockKey());438 assertEquals("MockProvider", cipher.getProvider().getName());439 // Using a different key...440 cipher.init(Cipher.ENCRYPT_MODE, new MockKey2());441 // ...results in a different provider.442 assertEquals("MockProvider2", cipher.getProvider().getName());443 } finally {444 Security.removeProvider(mockProvider.getName());445 Security.removeProvider(mockProvider2.getName());446 }447 }448 /**449 * http://b/29038928450 * If in a second call to init the current spi doesn't support the new specified451 * {@link AlgorithmParameterSpec}, look for another suitable spi.452 */453 public void test_init_onAlgorithmParameterTypeChange_reInitCipher() throws Exception {454 Provider mockProvider = new MockProvider("MockProvider") {455 public void setup() {456 put("Cipher.FOO",457 MockCipherSpi.SpecificAlgorithmParameterSpecTypes.class.getName());458 }459 };460 Provider mockProvider2 = new MockProvider("MockProvider2") {461 public void setup() {462 put("Cipher.FOO",463 MockCipherSpi.SpecificAlgorithmParameterSpecTypes2.class.getName());464 }465 };466 try {467 Security.addProvider(mockProvider);468 Security.addProvider(mockProvider2);469 Cipher cipher = Cipher.getInstance("FOO");470 cipher.init(Cipher.ENCRYPT_MODE,471 new MockKey(),472 new MockCipherSpi.MockAlgorithmParameterSpec());473 assertEquals("MockProvider", cipher.getProvider().getName());474 // Using a different AlgorithmParameterSpec...475 cipher.init(Cipher.ENCRYPT_MODE,476 new MockKey(),477 new MockCipherSpi.MockAlgorithmParameterSpec2());478 // ...results in a different provider.479 assertEquals("MockProvider2", cipher.getProvider().getName());480 } finally {481 Security.removeProvider(mockProvider.getName());482 Security.removeProvider(mockProvider2.getName());483 }484 }485 /**486 * http://b/29038928487 * If in a second call to init the current spi doesn't support the new specified488 * {@link AlgorithmParameters}, look for another suitable spi.489 */490 public void test_init_onAlgorithmParametersChange_reInitCipher() throws Exception {491 Provider mockProvider = new MockProvider("MockProvider") {492 public void setup() {493 put("Cipher.FOO",494 MockCipherSpi.SpecificAlgorithmParameterAesAlgorithm.class.getName());495 }496 };497 Provider mockProvider2 = new MockProvider("MockProvider2") {498 public void setup() {499 put("Cipher.FOO",500 MockCipherSpi.SpecificAlgorithmParametersDesAlgorithm.class.getName());501 }502 };503 try {504 Security.addProvider(mockProvider);505 Security.addProvider(mockProvider2);506 Cipher cipher = Cipher.getInstance("FOO");507 cipher.init(Cipher.ENCRYPT_MODE,508 new MockKey(),509 AlgorithmParameters.getInstance("AES"));510 assertEquals("MockProvider", cipher.getProvider().getName());511 // Using a different AlgorithmParameters...512 cipher.init(Cipher.ENCRYPT_MODE,513 new MockKey(),514 AlgorithmParameters.getInstance("DES"));515 // ...results in a different provider.516 assertEquals("MockProvider2", cipher.getProvider().getName());517 } finally {518 Security.removeProvider(mockProvider.getName());519 Security.removeProvider(mockProvider2.getName());520 }521 }522}...
TestPepInterceptorActions.java
Source:TestPepInterceptorActions.java
...13 */14package ddf.security.pep.interceptor;15import static org.junit.Assert.assertEquals;16import static org.junit.Assert.assertNotNull;17import static org.mockito.Matchers.isA;18import static org.mockito.Mockito.doAnswer;19import static org.mockito.Mockito.mock;20import static org.mockito.Mockito.when;21import javax.xml.namespace.QName;22import javax.xml.ws.handler.MessageContext;23import org.apache.cxf.binding.soap.model.SoapOperationInfo;24import org.apache.cxf.interceptor.security.AccessDeniedException;25import org.apache.cxf.message.Exchange;26import org.apache.cxf.message.Message;27import org.apache.cxf.service.model.BindingOperationInfo;28import org.apache.cxf.service.model.MessageInfo;29import org.apache.cxf.ws.addressing.Names;30import org.apache.cxf.ws.security.tokenstore.SecurityToken;31import org.junit.Rule;32import org.junit.Test;33import org.mockito.invocation.InvocationOnMock;34import org.mockito.stubbing.Answer;35import org.powermock.api.mockito.PowerMockito;36import org.powermock.core.classloader.annotations.PrepareForTest;37import org.powermock.modules.junit4.rule.PowerMockRule;38import ddf.security.Subject;39import ddf.security.assertion.SecurityAssertion;40import ddf.security.common.audit.SecurityLogger;41import ddf.security.permission.ActionPermission;42import ddf.security.service.SecurityManager;43import ddf.security.service.SecurityServiceException;44import ddf.security.service.impl.SecurityAssertionStore;45@PrepareForTest({SecurityAssertionStore.class, SecurityLogger.class})46public class TestPepInterceptorActions {47 @Rule48 public PowerMockRule rule = new PowerMockRule();49 @Test50 public void testMessageWithDefaultUriAction() throws SecurityServiceException {51 PEPAuthorizingInterceptor interceptor = new PEPAuthorizingInterceptor();52 SecurityManager mockSecurityManager = mock(SecurityManager.class);53 interceptor.setSecurityManager(mockSecurityManager);54 Message messageWithAction = mock(Message.class);55 SecurityAssertion mockSecurityAssertion = mock(SecurityAssertion.class);56 SecurityToken mockSecurityToken = mock(SecurityToken.class);57 Subject mockSubject = mock(Subject.class);58 assertNotNull(mockSecurityAssertion);59 PowerMockito.mockStatic(SecurityAssertionStore.class);60 PowerMockito.mockStatic(SecurityLogger.class);61 when(SecurityAssertionStore.getSecurityAssertion(messageWithAction))62 .thenReturn(mockSecurityAssertion);63 // SecurityLogger is already stubbed out64 when(mockSecurityAssertion.getSecurityToken()).thenReturn(mockSecurityToken);65 when(mockSecurityToken.getToken()).thenReturn(null);66 when(mockSecurityManager.getSubject(mockSecurityToken)).thenReturn(mockSubject);67 QName op = new QName("urn:catalog:query", "search", "ns1");68 QName port = new QName("urn:catalog:query", "query-port", "ns1");69 when(messageWithAction.get(MessageContext.WSDL_OPERATION)).thenReturn(op);70 when(messageWithAction.get(MessageContext.WSDL_PORT)).thenReturn(port);71 Exchange mockExchange = mock(Exchange.class);72 BindingOperationInfo mockBOI = mock(BindingOperationInfo.class);73 when(messageWithAction.getExchange()).thenReturn(mockExchange);74 when(mockExchange.get(BindingOperationInfo.class)).thenReturn(mockBOI);75 when(mockBOI.getExtensor(SoapOperationInfo.class)).thenReturn(null);76 doAnswer(new Answer<Boolean>() {77 @Override78 public Boolean answer(InvocationOnMock invocation) throws Throwable {79 ActionPermission perm = (ActionPermission) invocation.getArguments()[0];80 assertEquals("urn:catalog:query:query-port:searchRequest", perm.getAction());81 return true;82 }83 }).when(mockSubject).isPermitted(isA(ActionPermission.class));84 // This should work.85 interceptor.handleMessage(messageWithAction);86 PowerMockito.verifyStatic();87 }88 @Test89 public void testMessageWithDefaultUrlAction() throws SecurityServiceException {90 PEPAuthorizingInterceptor interceptor = new PEPAuthorizingInterceptor();91 SecurityManager mockSecurityManager = mock(SecurityManager.class);92 interceptor.setSecurityManager(mockSecurityManager);93 Message messageWithAction = mock(Message.class);94 SecurityAssertion mockSecurityAssertion = mock(SecurityAssertion.class);95 SecurityToken mockSecurityToken = mock(SecurityToken.class);96 Subject mockSubject = mock(Subject.class);97 assertNotNull(mockSecurityAssertion);98 PowerMockito.mockStatic(SecurityAssertionStore.class);99 PowerMockito.mockStatic(SecurityLogger.class);100 when(SecurityAssertionStore.getSecurityAssertion(messageWithAction))101 .thenReturn(mockSecurityAssertion);102 // SecurityLogger is already stubbed out103 when(mockSecurityAssertion.getSecurityToken()).thenReturn(mockSecurityToken);104 when(mockSecurityToken.getToken()).thenReturn(null);105 when(mockSecurityManager.getSubject(mockSecurityToken)).thenReturn(mockSubject);106 QName op = new QName("http://catalog/query/", "Search", "ns1");107 QName port = new QName("http://catalog/query/", "QueryPort", "ns1");108 when(messageWithAction.get(MessageContext.WSDL_OPERATION)).thenReturn(op);109 when(messageWithAction.get(MessageContext.WSDL_PORT)).thenReturn(port);110 Exchange mockExchange = mock(Exchange.class);111 BindingOperationInfo mockBOI = mock(BindingOperationInfo.class);112 when(messageWithAction.getExchange()).thenReturn(mockExchange);113 when(mockExchange.get(BindingOperationInfo.class)).thenReturn(mockBOI);114 when(mockBOI.getExtensor(SoapOperationInfo.class)).thenReturn(null);115 doAnswer(new Answer<Boolean>() {116 @Override117 public Boolean answer(InvocationOnMock invocation) throws Throwable {118 ActionPermission perm = (ActionPermission) invocation.getArguments()[0];119 assertEquals("http://catalog/query/QueryPort/SearchRequest", perm.getAction());120 return true;121 }122 }).when(mockSubject).isPermitted(isA(ActionPermission.class));123 // This should work.124 interceptor.handleMessage(messageWithAction);125 PowerMockito.verifyStatic();126 }127 @Test128 public void testMessageWithMessageAction() throws SecurityServiceException {129 PEPAuthorizingInterceptor interceptor = new PEPAuthorizingInterceptor();130 SecurityManager mockSecurityManager = mock(SecurityManager.class);131 interceptor.setSecurityManager(mockSecurityManager);132 Message messageWithAction = mock(Message.class);133 SecurityAssertion mockSecurityAssertion = mock(SecurityAssertion.class);134 SecurityToken mockSecurityToken = mock(SecurityToken.class);135 Subject mockSubject = mock(Subject.class);136 assertNotNull(mockSecurityAssertion);137 PowerMockito.mockStatic(SecurityAssertionStore.class);138 PowerMockito.mockStatic(SecurityLogger.class);139 when(SecurityAssertionStore.getSecurityAssertion(messageWithAction))140 .thenReturn(mockSecurityAssertion);141 // SecurityLogger is already stubbed out142 when(mockSecurityAssertion.getSecurityToken()).thenReturn(mockSecurityToken);143 when(mockSecurityToken.getToken()).thenReturn(null);144 when(mockSecurityManager.getSubject(mockSecurityToken)).thenReturn(mockSubject);145 MessageInfo mockMessageInfo = mock(MessageInfo.class);146 when(messageWithAction.get(MessageInfo.class.getName())).thenReturn(mockMessageInfo);147 when(mockMessageInfo.getExtensionAttribute(148 new QName(Names.WSA_NAMESPACE_WSDL_METADATA, Names.WSAW_ACTION_NAME)))149 .thenReturn("urn:catalog:query:query-port:search");150 doAnswer(new Answer<Boolean>() {151 @Override152 public Boolean answer(InvocationOnMock invocation) throws Throwable {153 ActionPermission perm = (ActionPermission) invocation.getArguments()[0];154 assertEquals("urn:catalog:query:query-port:search", perm.getAction());155 return true;156 }157 }).when(mockSubject).isPermitted(isA(ActionPermission.class));158 // This should work.159 interceptor.handleMessage(messageWithAction);160 PowerMockito.verifyStatic();161 }162 @Test163 public void testMessageWithOperationAction() throws SecurityServiceException {164 PEPAuthorizingInterceptor interceptor = new PEPAuthorizingInterceptor();165 SecurityManager mockSecurityManager = mock(SecurityManager.class);166 interceptor.setSecurityManager(mockSecurityManager);167 Message messageWithAction = mock(Message.class);168 SecurityAssertion mockSecurityAssertion = mock(SecurityAssertion.class);169 SecurityToken mockSecurityToken = mock(SecurityToken.class);170 Subject mockSubject = mock(Subject.class);171 assertNotNull(mockSecurityAssertion);172 PowerMockito.mockStatic(SecurityAssertionStore.class);173 PowerMockito.mockStatic(SecurityLogger.class);174 when(SecurityAssertionStore.getSecurityAssertion(messageWithAction))175 .thenReturn(mockSecurityAssertion);176 // SecurityLogger is already stubbed out177 when(mockSecurityAssertion.getSecurityToken()).thenReturn(mockSecurityToken);178 when(mockSecurityToken.getToken()).thenReturn(null);179 when(mockSecurityManager.getSubject(mockSecurityToken)).thenReturn(mockSubject);180 Exchange mockExchange = mock(Exchange.class);181 BindingOperationInfo mockBOI = mock(BindingOperationInfo.class);182 SoapOperationInfo mockSOI = mock(SoapOperationInfo.class);183 when(messageWithAction.getExchange()).thenReturn(mockExchange);184 when(mockExchange.get(BindingOperationInfo.class)).thenReturn(mockBOI);185 when(mockBOI.getExtensor(SoapOperationInfo.class)).thenReturn(mockSOI);186 when(mockSOI.getAction()).thenReturn("urn:catalog:query:query-port:search");187 doAnswer(new Answer<Boolean>() {188 @Override189 public Boolean answer(InvocationOnMock invocation) throws Throwable {190 ActionPermission perm = (ActionPermission) invocation.getArguments()[0];191 assertEquals("urn:catalog:query:query-port:search", perm.getAction());192 return true;193 }194 }).when(mockSubject).isPermitted(isA(ActionPermission.class));195 // This should work.196 interceptor.handleMessage(messageWithAction);197 PowerMockito.verifyStatic();198 }199 @Test(expected = AccessDeniedException.class)200 public void testMessageWithNoAction() throws SecurityServiceException {201 PEPAuthorizingInterceptor interceptor = new PEPAuthorizingInterceptor();202 SecurityManager mockSecurityManager = mock(SecurityManager.class);203 interceptor.setSecurityManager(mockSecurityManager);204 Message messageWithoutAction = mock(Message.class);205 SecurityAssertion mockSecurityAssertion = mock(SecurityAssertion.class);206 SecurityToken mockSecurityToken = mock(SecurityToken.class);207 Subject mockSubject = mock(Subject.class);208 assertNotNull(mockSecurityAssertion);209 PowerMockito.mockStatic(SecurityAssertionStore.class);210 PowerMockito.mockStatic(SecurityLogger.class);211 when(SecurityAssertionStore.getSecurityAssertion(messageWithoutAction))212 .thenReturn(mockSecurityAssertion);213 // SecurityLogger is already stubbed out214 when(mockSecurityAssertion.getSecurityToken()).thenReturn(mockSecurityToken);215 when(mockSecurityToken.getToken()).thenReturn(null);216 when(mockSecurityManager.getSubject(mockSecurityToken)).thenReturn(mockSubject);217 Exchange mockExchange = mock(Exchange.class);218 BindingOperationInfo mockBOI = mock(BindingOperationInfo.class);219 when(messageWithoutAction.getExchange()).thenReturn(mockExchange);220 when(mockExchange.get(BindingOperationInfo.class)).thenReturn(mockBOI);221 when(mockBOI.getExtensor(SoapOperationInfo.class)).thenReturn(null);222 when(mockSubject.isPermitted(isA(ActionPermission.class))).thenReturn(false);223 // This should throw an exception.224 interceptor.handleMessage(messageWithoutAction);225 PowerMockito.verifyStatic();226 }227}...
test_minitest_mock.rb
Source:test_minitest_mock.rb
1require "minitest/autorun"2class TestMinitestMock < Minitest::Test3 parallelize_me!4 def setup5 @mock = Minitest::Mock.new.expect(:foo, nil)6 @mock.expect(:meaning_of_life, 42)7 end8 def test_create_stub_method9 assert_nil @mock.foo10 end11 def test_allow_return_value_specification12 assert_equal 42, @mock.meaning_of_life13 end14 def test_blow_up_if_not_called15 @mock.foo16 util_verify_bad "expected meaning_of_life() => 42"17 end18 def test_not_blow_up_if_everything_called19 @mock.foo20 @mock.meaning_of_life21 assert_mock @mock22 end23 def test_allow_expectations_to_be_added_after_creation24 @mock.expect(:bar, true)25 assert @mock.bar26 end27 def test_not_verify_if_new_expected_method_is_not_called28 @mock.foo29 @mock.meaning_of_life30 @mock.expect(:bar, true)31 util_verify_bad "expected bar() => true"32 end33 def test_blow_up_on_wrong_number_of_arguments34 @mock.foo35 @mock.meaning_of_life36 @mock.expect(:sum, 3, [1, 2])37 e = assert_raises ArgumentError do38 @mock.sum39 end40 assert_equal "mocked method :sum expects 2 arguments, got 0", e.message41 end42 def test_return_mock_does_not_raise43 retval = Minitest::Mock.new44 mock = Minitest::Mock.new45 mock.expect(:foo, retval)46 mock.foo47 assert_mock mock48 end49 def test_mock_args_does_not_raise50 skip "non-opaque use of ==" if maglev?51 arg = Minitest::Mock.new52 mock = Minitest::Mock.new53 mock.expect(:foo, nil, [arg])54 mock.foo(arg)55 assert_mock mock56 end57 def test_set_expectation_on_special_methods58 mock = Minitest::Mock.new59 mock.expect :object_id, "received object_id"60 assert_equal "received object_id", mock.object_id61 mock.expect :respond_to_missing?, "received respond_to_missing?"62 assert_equal "received respond_to_missing?", mock.respond_to_missing?63 mock.expect :===, "received ==="64 assert_equal "received ===", mock.===65 mock.expect :inspect, "received inspect"66 assert_equal "received inspect", mock.inspect67 mock.expect :to_s, "received to_s"68 assert_equal "received to_s", mock.to_s69 mock.expect :public_send, "received public_send"70 assert_equal "received public_send", mock.public_send71 mock.expect :send, "received send"72 assert_equal "received send", mock.send73 assert_mock mock74 end75 def test_expectations_can_be_satisfied_via_send76 @mock.send :foo77 @mock.send :meaning_of_life78 assert_mock @mock79 end80 def test_expectations_can_be_satisfied_via_public_send81 skip "Doesn't run on 1.8" if RUBY_VERSION < "1.9"82 @mock.public_send :foo83 @mock.public_send :meaning_of_life84 assert_mock @mock85 end86 def test_blow_up_on_wrong_arguments87 @mock.foo88 @mock.meaning_of_life89 @mock.expect(:sum, 3, [1, 2])90 e = assert_raises MockExpectationError do91 @mock.sum(2, 4)92 end93 exp = "mocked method :sum called with unexpected arguments [2, 4]"94 assert_equal exp, e.message95 end96 def test_expect_with_non_array_args97 e = assert_raises ArgumentError do98 @mock.expect :blah, 3, false99 end100 assert_equal "args must be an array", e.message101 end102 def test_respond_appropriately103 assert @mock.respond_to?(:foo)104 assert @mock.respond_to?(:foo, true)105 assert @mock.respond_to?("foo")106 assert !@mock.respond_to?(:bar)107 end108 def test_no_method_error_on_unexpected_methods109 e = assert_raises NoMethodError do110 @mock.bar111 end112 expected = "unmocked method :bar, expected one of [:foo, :meaning_of_life]"113 assert_equal expected, e.message114 end115 def test_assign_per_mock_return_values116 a = Minitest::Mock.new117 b = Minitest::Mock.new118 a.expect(:foo, :a)119 b.expect(:foo, :b)120 assert_equal :a, a.foo121 assert_equal :b, b.foo122 end123 def test_do_not_create_stub_method_on_new_mocks124 a = Minitest::Mock.new125 a.expect(:foo, :a)126 assert !Minitest::Mock.new.respond_to?(:foo)127 end128 def test_mock_is_a_blank_slate129 @mock.expect :kind_of?, true, [String]130 @mock.expect :==, true, [1]131 assert @mock.kind_of?(String), "didn't mock :kind_of\?"132 assert @mock == 1, "didn't mock :=="133 end134 def test_verify_allows_called_args_to_be_loosely_specified135 mock = Minitest::Mock.new136 mock.expect :loose_expectation, true, [Integer]137 mock.loose_expectation 1138 assert_mock mock139 end140 def test_verify_raises_with_strict_args141 mock = Minitest::Mock.new142 mock.expect :strict_expectation, true, [2]143 e = assert_raises MockExpectationError do144 mock.strict_expectation 1145 end146 exp = "mocked method :strict_expectation called with unexpected arguments [1]"147 assert_equal exp, e.message148 end149 def test_method_missing_empty150 mock = Minitest::Mock.new151 mock.expect :a, nil152 mock.a153 e = assert_raises MockExpectationError do154 mock.a155 end156 assert_equal "No more expects available for :a: []", e.message157 end158 def test_same_method_expects_are_verified_when_all_called159 mock = Minitest::Mock.new160 mock.expect :foo, nil, [:bar]161 mock.expect :foo, nil, [:baz]162 mock.foo :bar163 mock.foo :baz164 assert_mock mock165 end166 def test_same_method_expects_blow_up_when_not_all_called167 mock = Minitest::Mock.new168 mock.expect :foo, nil, [:bar]169 mock.expect :foo, nil, [:baz]170 mock.foo :bar171 e = assert_raises(MockExpectationError) { mock.verify }172 exp = "expected foo(:baz) => nil, got [foo(:bar) => nil]"173 assert_equal exp, e.message174 end175 def test_same_method_expects_with_same_args_blow_up_when_not_all_called176 mock = Minitest::Mock.new177 mock.expect :foo, nil, [:bar]178 mock.expect :foo, nil, [:bar]179 mock.foo :bar180 e = assert_raises(MockExpectationError) { mock.verify }181 exp = "expected foo(:bar) => nil, got [foo(:bar) => nil]"182 assert_equal exp, e.message183 end184 def test_verify_passes_when_mock_block_returns_true185 mock = Minitest::Mock.new186 mock.expect :foo, nil do187 true188 end189 mock.foo190 assert_mock mock191 end192 def test_mock_block_is_passed_function_params193 arg1, arg2, arg3 = :bar, [1, 2, 3], { :a => "a" }194 mock = Minitest::Mock.new195 mock.expect :foo, nil do |a1, a2, a3|196 a1 == arg1 && a2 == arg2 && a3 == arg3197 end198 mock.foo arg1, arg2, arg3199 assert_mock mock200 end201 def test_mock_block_is_passed_function_block202 mock = Minitest::Mock.new203 block = proc { "bar" }204 mock.expect :foo, nil do |arg, &blk|205 arg == "foo" &&206 blk == block207 end208 mock.foo "foo", &block209 assert_mock mock210 end211 def test_verify_fails_when_mock_block_returns_false212 mock = Minitest::Mock.new213 mock.expect :foo, nil do214 false215 end216 e = assert_raises(MockExpectationError) { mock.foo }217 exp = "mocked method :foo failed block w/ []"218 assert_equal exp, e.message219 end220 def test_mock_block_throws_if_args_passed221 mock = Minitest::Mock.new222 e = assert_raises(ArgumentError) do223 mock.expect :foo, nil, [:a, :b, :c] do224 true225 end226 end227 exp = "args ignored when block given"228 assert_equal exp, e.message229 end230 def test_mock_returns_retval_when_called_with_block231 mock = Minitest::Mock.new232 mock.expect(:foo, 32) do233 true234 end235 rs = mock.foo236 assert_equal rs, 32237 end238 def util_verify_bad exp239 e = assert_raises MockExpectationError do240 @mock.verify241 end242 assert_equal exp, e.message243 end244 def test_mock_called_via_send245 mock = Minitest::Mock.new246 mock.expect(:foo, true)247 mock.send :foo248 assert_mock mock249 end250 def test_mock_called_via___send__251 mock = Minitest::Mock.new252 mock.expect(:foo, true)253 mock.__send__ :foo254 assert_mock mock255 end256 def test_mock_called_via_send_with_args257 mock = Minitest::Mock.new258 mock.expect(:foo, true, [1, 2, 3])259 mock.send(:foo, 1, 2, 3)260 assert_mock mock261 end262end263require "minitest/metametameta"264class TestMinitestStub < Minitest::Test265 parallelize_me!266 def setup267 super268 Minitest::Test.reset269 @tc = Minitest::Test.new "fake tc"270 @assertion_count = 1271 end272 def teardown273 super274 assert_equal @assertion_count, @tc.assertions275 end276 class Time277 def self.now278 24279 end280 end281 def assert_stub val_or_callable282 @assertion_count += 1283 t = Time.now.to_i284 Time.stub :now, val_or_callable do285 @tc.assert_equal 42, Time.now286 end287 @tc.assert_operator Time.now.to_i, :>=, t288 end289 def test_stub_private_module_method290 @assertion_count += 1291 t0 = Time.now292 self.stub :sleep, nil do293 @tc.assert_nil sleep(10)294 end295 @tc.assert_operator Time.now - t0, :<=, 1296 end297 def test_stub_private_module_method_indirect298 @assertion_count += 1299 fail_clapper = Class.new do300 def fail_clap301 raise302 :clap303 end304 end.new305 fail_clapper.stub :raise, nil do |safe_clapper|306 @tc.assert_equal :clap, safe_clapper.fail_clap # either form works307 @tc.assert_equal :clap, fail_clapper.fail_clap # yay closures308 end309 end310 def test_stub_public_module_method311 Math.stub :log10, :stubbed do312 @tc.assert_equal :stubbed, Math.log10(1000)313 end314 end315 def test_stub_value316 assert_stub 42317 end318 def test_stub_block319 assert_stub lambda { 42 }320 end321 def test_stub_block_args322 @assertion_count += 1323 t = Time.now.to_i324 Time.stub :now, lambda { |n| n * 2 } do325 @tc.assert_equal 42, Time.now(21)326 end327 @tc.assert_operator Time.now.to_i, :>=, t328 end329 def test_stub_callable330 obj = Object.new331 def obj.call332 42333 end334 assert_stub obj335 end336 def test_stub_yield_self337 obj = "foo"338 val = obj.stub :to_s, "bar" do |s|339 s.to_s340 end341 @tc.assert_equal "bar", val342 end343 def test_dynamic_method344 @assertion_count = 2345 dynamic = Class.new do346 def self.respond_to? meth347 meth == :found348 end349 def self.method_missing meth, *args, &block350 if meth == :found351 false352 else353 super354 end355 end356 end357 val = dynamic.stub(:found, true) do |s|358 s.found359 end360 @tc.assert_equal true, val361 @tc.assert_equal false, dynamic.found362 end363 def test_mock_with_yield364 mock = Minitest::Mock.new365 mock.expect(:write, true) do366 true367 end368 rs = nil369 File.stub :open, true, mock do370 File.open "foo.txt", "r" do |f|371 rs = f.write372 end373 end374 @tc.assert_equal true, rs375 end376end...
mock_test.rb
Source:mock_test.rb
1require File.join(File.dirname(__FILE__), "..", "test_helper")2require 'mocha/mock'3require 'mocha/expectation_error'4require 'set'5require 'simple_counter'6class MockTest < Test::Unit::TestCase7 8 include Mocha9 10 def test_should_set_single_expectation11 mock = Mock.new12 mock.expects(:method1).returns(1)13 assert_nothing_raised(ExpectationError) do14 assert_equal 1, mock.method115 end16 end 17 def test_should_build_and_store_expectations18 mock = Mock.new19 expectation = mock.expects(:method1)20 assert_not_nil expectation21 assert_equal [expectation], mock.expectations.to_a22 end23 24 def test_should_not_stub_everything_by_default25 mock = Mock.new26 assert_equal false, mock.everything_stubbed27 end28 29 def test_should_stub_everything30 mock = Mock.new31 mock.stub_everything32 assert_equal true, mock.everything_stubbed33 end34 35 def test_should_be_able_to_extend_mock_object_with_module36 mock = Mock.new37 assert_nothing_raised(ExpectationError) { mock.extend(Module.new) }38 end39 40 def test_should_be_equal41 mock = Mock.new42 assert_equal true, mock.eql?(mock)43 end44 45 if RUBY_VERSION < '1.9'46 OBJECT_METHODS = STANDARD_OBJECT_PUBLIC_INSTANCE_METHODS.reject { |m| m =~ /^__.*__$/ }47 else48 OBJECT_METHODS = STANDARD_OBJECT_PUBLIC_INSTANCE_METHODS.reject { |m| m =~ /^__.*__$/ || m == :object_id }49 end50 51 def test_should_be_able_to_mock_standard_object_methods52 mock = Mock.new53 OBJECT_METHODS.each { |method| mock.__expects__(method.to_sym).returns(method) }54 OBJECT_METHODS.each { |method| assert_equal method, mock.__send__(method.to_sym) }55 assert mock.__verified__?56 end57 58 def test_should_be_able_to_stub_standard_object_methods59 mock = Mock.new60 OBJECT_METHODS.each { |method| mock.__stubs__(method.to_sym).returns(method) }61 OBJECT_METHODS.each { |method| assert_equal method, mock.__send__(method.to_sym) }62 end63 64 def test_should_create_and_add_expectations65 mock = Mock.new66 expectation1 = mock.expects(:method1)67 expectation2 = mock.expects(:method2)68 assert_equal [expectation1, expectation2].to_set, mock.expectations.to_set69 end70 71 def test_should_pass_backtrace_into_expectation72 mock = Mock.new73 backtrace = Object.new74 expectation = mock.expects(:method1, backtrace)75 assert_equal backtrace, expectation.backtrace76 end77 78 def test_should_pass_backtrace_into_stub79 mock = Mock.new80 backtrace = Object.new81 stub = mock.stubs(:method1, backtrace)82 assert_equal backtrace, stub.backtrace83 end84 85 def test_should_create_and_add_stubs86 mock = Mock.new87 stub1 = mock.stubs(:method1)88 stub2 = mock.stubs(:method2)89 assert_equal [stub1, stub2].to_set, mock.expectations.to_set90 end91 92 def test_should_invoke_expectation_and_return_result93 mock = Mock.new94 mock.expects(:my_method).returns(:result)95 result = mock.my_method96 assert_equal :result, result97 end98 99 def test_should_not_raise_error_if_stubbing_everything100 mock = Mock.new101 mock.stub_everything102 result = nil103 assert_nothing_raised(ExpectationError) do104 result = mock.unexpected_method105 end106 assert_nil result107 end108 109 def test_should_raise_assertion_error_for_unexpected_method_call110 mock = Mock.new111 error = assert_raise(ExpectationError) do112 mock.unexpected_method_called(:my_method, :argument1, :argument2)113 end114 assert_match(/unexpected invocation/, error.message)115 assert_match(/my_method/, error.message)116 assert_match(/argument1/, error.message)117 assert_match(/argument2/, error.message)118 end119 120 def test_should_not_verify_successfully_because_not_all_expectations_have_been_satisfied121 mock = Mock.new122 mock.expects(:method1)123 mock.expects(:method2)124 mock.method1125 assert !mock.__verified__?126 end127 128 def test_should_increment_assertion_counter_for_every_verified_expectation129 mock = Mock.new130 131 mock.expects(:method1)132 mock.method1133 134 mock.expects(:method2)135 mock.method2136 137 assertion_counter = SimpleCounter.new138 139 mock.__verified__?(assertion_counter)140 141 assert_equal 2, assertion_counter.count142 end143 144 def test_should_yield_supplied_parameters_to_block145 mock = Mock.new146 parameters_for_yield = [1, 2, 3]147 mock.expects(:method1).yields(*parameters_for_yield)148 yielded_parameters = nil149 mock.method1() { |*parameters| yielded_parameters = parameters }150 assert_equal parameters_for_yield, yielded_parameters151 end152 153 def test_should_set_up_multiple_expectations_with_return_values154 mock = Mock.new155 mock.expects(:method1 => :result1, :method2 => :result2)156 assert_equal :result1, mock.method1157 assert_equal :result2, mock.method2158 end159 160 def test_should_set_up_multiple_stubs_with_return_values161 mock = Mock.new162 mock.stubs(:method1 => :result1, :method2 => :result2)163 assert_equal :result1, mock.method1164 assert_equal :result2, mock.method2165 end166 167 def test_should_keep_returning_specified_value_for_stubs168 mock = Mock.new169 mock.stubs(:method1).returns(1)170 assert_equal 1, mock.method1171 assert_equal 1, mock.method1172 end173 174 def test_should_keep_returning_specified_value_for_expects175 mock = Mock.new176 mock.expects(:method1).times(2).returns(1)177 assert_equal 1, mock.method1178 assert_equal 1, mock.method1179 end180 181 def test_should_match_most_recent_call_to_expects182 mock = Mock.new183 mock.expects(:method1).returns(0)184 mock.expects(:method1).returns(1)185 assert_equal 1, mock.method1186 end187 def test_should_match_most_recent_call_to_stubs188 mock = Mock.new189 mock.stubs(:method1).returns(0)190 mock.stubs(:method1).returns(1)191 assert_equal 1, mock.method1192 end193 def test_should_match_most_recent_call_to_stubs_or_expects194 mock = Mock.new195 mock.stubs(:method1).returns(0)196 mock.expects(:method1).returns(1)197 assert_equal 1, mock.method1198 end199 def test_should_match_most_recent_call_to_expects_or_stubs200 mock = Mock.new201 mock.expects(:method1).returns(0)202 mock.stubs(:method1).returns(1)203 assert_equal 1, mock.method1204 end205 206 def test_should_respond_to_expected_method207 mock = Mock.new208 mock.expects(:method1)209 assert_equal true, mock.respond_to?(:method1)210 end211 212 def test_should_not_respond_to_unexpected_method213 mock = Mock.new214 assert_equal false, mock.respond_to?(:method1)215 end216 217 def test_should_respond_to_methods_which_the_responder_does_responds_to218 instance = Class.new do219 define_method(:respond_to?) { |symbol| true }220 end.new221 mock = Mock.new222 mock.responds_like(instance)223 assert_equal true, mock.respond_to?(:invoked_method)224 end225 226 def test_should_not_respond_to_methods_which_the_responder_does_not_responds_to227 instance = Class.new do228 define_method(:respond_to?) { |symbol| false }229 end.new230 mock = Mock.new231 mock.responds_like(instance)232 assert_equal false, mock.respond_to?(:invoked_method)233 end234 235 def test_should_return_itself_to_allow_method_chaining236 mock = Mock.new237 assert_same mock.responds_like(Object.new), mock238 end239 240 def test_should_not_raise_no_method_error_if_mock_is_not_restricted_to_respond_like_a_responder241 instance = Class.new do242 define_method(:respond_to?) { true }243 end.new244 mock = Mock.new245 mock.stubs(:invoked_method)246 assert_nothing_raised(NoMethodError) { mock.invoked_method }247 end248 249 def test_should_not_raise_no_method_error_if_responder_does_respond_to_invoked_method250 instance = Class.new do251 define_method(:respond_to?) { |symbol| true }252 end.new253 mock = Mock.new254 mock.responds_like(instance)255 mock.stubs(:invoked_method)256 assert_nothing_raised(NoMethodError) { mock.invoked_method }257 end258 259 def test_should_raise_no_method_error_if_responder_does_not_respond_to_invoked_method260 instance = Class.new do261 define_method(:respond_to?) { |symbol| false }262 define_method(:mocha_inspect) { 'mocha_inspect' }263 end.new264 mock = Mock.new265 mock.responds_like(instance)266 mock.stubs(:invoked_method)267 assert_raises(NoMethodError) { mock.invoked_method }268 end269 270 def test_should_raise_no_method_error_with_message_indicating_that_mock_is_constrained_to_respond_like_responder271 instance = Class.new do272 define_method(:respond_to?) { |symbol| false }273 define_method(:mocha_inspect) { 'mocha_inspect' }274 end.new275 mock = Mock.new276 mock.responds_like(instance)277 mock.stubs(:invoked_method)278 begin279 mock.invoked_method280 rescue NoMethodError => e281 assert_match(/which responds like mocha_inspect/, e.message)282 end283 end284 285 def test_should_handle_respond_to_with_private_methods_param_without_error286 mock = Mock.new287 assert_nothing_raised{ mock.respond_to?(:object_id, false) }288 end289 290 def test_should_respond_to_any_method_if_stubbing_everything291 mock = Mock.new292 mock.stub_everything293 assert mock.respond_to?(:abc)294 assert mock.respond_to?(:xyz)295 end296 297end...
mock
Using AI Code Generation
1$mockGenerator = new \Atoum\Mock\Generator();2$mockGenerator->generate('MyClass');3$mockGenerator = new \mageekguy\atoum\mock\generator();4$mockGenerator->generate('MyClass');5$mockGenerator = new \Atoum\Mock\Generator();6$mockGenerator->generate('MyClass');7$mockGenerator = new \mageekguy\atoum\mock\generator();8$mockGenerator->generate('MyClass');9$mockGenerator = new \Atoum\Mock\Generator();10$mockGenerator->generate('MyClass');11$mockGenerator = new \mageekguy\atoum\mock\generator();12$mockGenerator->generate('MyClass');13$mockGenerator = new \Atoum\Mock\Generator();14$mockGenerator->generate('MyClass');15$mockGenerator = new \mageekguy\atoum\mock\generator();16$mockGenerator->generate('MyClass');17$mockGenerator = new \Atoum\Mock\Generator();18$mockGenerator->generate('MyClass');19$mockGenerator = new \mageekguy\atoum\mock\generator();20$mockGenerator->generate('MyClass');21$mockGenerator = new \Atoum\Mock\Generator();22$mockGenerator->generate('MyClass');
mock
Using AI Code Generation
1$mock = new \mock\Atoum\Mock\ClassMock();2$mock->getMockController()->getFoo = 42;3$this->integer($mock->getFoo())->isIdenticalTo(42);4$mock = new \mock\Atoum\Mock\ClassMock();5$this->integer($mock->getFoo())->isIdenticalTo(42);6$mock = new \mock\Atoum\Mock\ClassMock();7$mock->getMockController()->getFoo = 42;8$this->integer($mock->getFoo())->isIdenticalTo(42);9$mock = new \mock\Atoum\Mock\ClassMock();10$this->integer($mock->getFoo())->isIdenticalTo(42);11$mockGenerator->setNamespace('myNamespace');12$mock = new \mock\Atoum\Mock\ClassMock();13$mock->getMockController()->getFoo = 42;14$this->integer($mock->getFoo())->isIdenticalTo(42);15$mockGenerator->setNamespace('myNamespace');16$mock = new \mock\Atoum\Mock\ClassMock();17$this->integer($mock->getFoo())->isIdenticalTo(42);
mock
Using AI Code Generation
1$mock = new \mock\Atoum\Mock();2$mock = new \mock\Atoum\Mock();3$mock = new \mock\Atoum\Mock();4$mock = new \mock\Atoum\Mock();5$mock = new \mock\Atoum\Mock();6$mock = new \mock\Atoum\Mock();7$mock = new \mock\Atoum\Mock();8$mock = new \mock\Atoum\Mock();9$mock = new \mock\Atoum\Mock();10$mock = new \mock\Atoum\Mock();11$mock = new \mock\Atoum\Mock();12$mock = new \mock\Atoum\Mock();13$mock = new \mock\Atoum\Mock();14$mock = new \mock\Atoum\Mock();15$mock = new \mock\Atoum\Mock();16$mock = new \mock\Atoum\Mock();17$mock = new \mock\Atoum\Mock();18$mock = new \mock\Atoum\Mock();
mock
Using AI Code Generation
1$mock = new Atoum\Mock\Mock();2$mock->getMockController()->getFoo = 'bar';3$mock = new Atoum\Mock\Mock();4$mock->getMockController()->getFoo = 'bar';5$mock = new Atoum\Mock\Mock();6$mock->getMockController()->getFoo = 'bar';7$mock = new Atoum\Mock\Mock();8$mock->getMockController()->getFoo = 'bar';9$mock = new Atoum\Mock\Mock();10$mock->getMockController()->getFoo = 'bar';11$mock = new Atoum\Mock\Mock();12$mock->getMockController()->getFoo = 'bar';13$mock = new Atoum\Mock\Mock();14$mock->getMockController()->getFoo = 'bar';15$mock = new Atoum\Mock\Mock();16$mock->getMockController()->getFoo = 'bar';17$mock = new Atoum\Mock\Mock();18$mock->getMockController()->getFoo = 'bar';19$mock->getFoo();
mock
Using AI Code Generation
1{2 public function testMock()3 {4 $mock = new \mock\atoum\test();5 $this->assert->object($mock)->isInstanceOf('atoum\test');6 }7}8{9 public function testMock()10 {11 $mock = new \mock\atoum\test();12 $this->assert->object($mock)->isInstanceOf('atoum\test');13 }14}15{16 public function testMock()17 {18 $mock = new \mock\atoum\test();19 $this->assert->object($mock)->isInstanceOf('atoum\test');20 }21}22{23 public function testMock()24 {25 $mock = new \mock\atoum\test();26 $this->assert->object($mock)->isInstanceOf('atoum\test');27 }28}29{30 public function testMock()31 {32 $mock = new \mock\atoum\test();33 $this->assert->object($mock)->isInstanceOf('atoum\test');34 }35}36{37 public function testMock()38 {39 $mock = new \mock\atoum\test();40 $this->assert->object($mock)->isInstanceOf('atoum\test');41 }42}43{44 public function testMock()45 {46 $mock = new \mock\atoum\test();
mock
Using AI Code Generation
1use Atoum\Mock\ClassMock;2use Atoum\Mock\Mock;3$mock = new ClassMock();4$mock->setMockClass('Atoum\Mock\Mock');5$mock->getMockController()->isMockController = true;6$mock->getMockController()->isMock = true;7use Atoum\Mock\ClassMock;8use Atoum\Mock\Mock;9$mock = new Mock();10$mock->getMockController()->isMockController = true;11$mock->getMockController()->isMock = true;12use Atoum\Mock\ClassMock;13use Atoum\Mock\Mock;14$mock = new Mock();15$mock->getMockController()->isMockController = true;16$mock->getMockController()->isMock = true;17use Atoum\Mock\ClassMock;18use Atoum\Mock\Mock;19$mock = new Mock();20$mock->getMockController()->isMockController = true;21$mock->getMockController()->isMock = true;22use Atoum\Mock\ClassMock;23use Atoum\Mock\Mock;24$mock = new Mock();25$mock->getMockController()->isMockController = true;26$mock->getMockController()->isMock = true;
mock
Using AI Code Generation
1require_once 'vendor/autoload.php';2use \mageekguy\atoum;3{4 public function testAssert()5 {6 $this->assert(true);7 }8}9{10 public function testAssert()11 {12 $this->assert(true);13 }14}15require_once 'vendor/autoload.php';16use \mageekguy\atoum;17{18 public function testAssert()19 {20 $this->assert(true);21 }22}23{24 public function testAssert()25 {26 $this->assert(true);27 }28}29require_once 'vendor/autoload.php';30use \mageekguy\atoum;31{32 public function testAssert()33 {34 $this->assert(true);35 }36}37{38 public function testAssert()39 {40 $this->assert(true);41 }42}43require_once 'vendor/autoload.php';44use \mageekguy\atoum;45{46 public function testAssert()47 {48 $this->assert(true);49 }50}51{52 public function testAssert()53 {54 $this->assert(true);55 }56}57require_once 'vendor/autoload.php';58use \mageekguy\atoum;59{60 public function testAssert()61 {
mock
Using AI Code Generation
1$mock = new mock\controller();2$mock->getMock('Atoum\Mock\ClassMock');3$mock->getMockController()->__construct = function($class) {4};5$class = new mock\classMock();6$mock = new mock\controller();7$mock->getMock('Atoum\Mock\ClassMock');8$mock->getMockController()->__construct = function($class) {9};10$class = new mock\classMock();11$mock = new mock\controller();12$mock->getMock('Atoum\Mock\ClassMock');13$mock->getMockController()->__construct = function($class) {14};15$class = new mock\classMock();
mock
Using AI Code Generation
1$mock = new Atoum\Mock\ClassMock('testClass');2$mock->getMockController()->testMethod = 'test';3$mock->getMockController()->testMethod2 = 'test2';4$mock->getMockController()->testMethod3 = 'test3';5$mock->getMockController()->testMethod4 = 'test4';6$mock->getMockController()->testMethod5 = 'test5';7$mock->getMockController()->testMethod6 = 'test6';8$mock->getMockController()->testMethod7 = 'test7';9$mock->getMockController()->testMethod8 = 'test8';10$mock->getMockController()->testMethod9 = 'test9';11$mock->getMockController()->testMethod10 = 'test10';12$mock->getMockController()->testMethod11 = 'test11';13$mock->getMockController()->testMethod12 = 'test12';14$mock->getMockController()->testMethod13 = 'test13';15$mock->getMockController()->testMethod14 = 'test14';16$mock->getMockController()->testMethod15 = 'test15';17$mock->getMockController()->testMethod16 = 'test16';18$mock->getMockController()->testMethod17 = 'test17';19$mock->getMockController()->testMethod18 = 'test18';20$mock->getMockController()->testMethod19 = 'test19';21$mock->getMockController()->testMethod20 = 'test20';22$mock->getMockController()->testMethod21 = 'test21';23$mock->getMockController()->testMethod22 = 'test22';24$mock->getMockController()->testMethod23 = 'test23';25$mock->getMockController()->testMethod24 = 'test24';26$mock->getMockController()->testMethod25 = 'test25';27$mock->getMockController()->testMethod26 = 'test26';28$mock->getMockController()->testMethod27 = 'test27';29$mock->getMockController()->testMethod28 = 'test28';30$mock->getMockController()->testMethod29 = 'test29';31$mock->getMockController()->testMethod30 = 'test30';32$mock->getMockController()->testMethod31 = 'test31';33$mock->getMockController()->testMethod32 = 'test32';34$mock->getMockController()->testMethod33 = 'test33';35$mock->getMockController()->testMethod34
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Trigger Selenium automation tests on a cloud-based Grid of 3000+ real browsers and operating systems.
Test now for FreeGet 100 minutes of automation test minutes FREE!!