How to use then method of org.jmock.AbstractExpectations class

Best Jmock-library code snippet using org.jmock.AbstractExpectations.then

Source:JythonDropboxRecoveryTest.java Github

copy

Full Screen

...145 * Specifies what properties should be overriden for this test case.146 */147 protected HashMap<String, String> overrideProperties;148 /**149 * If true, than autorecovery should take place. If not, then transaction should be rolled back, and recovery artifacts removed.150 */151 protected boolean canRecoverFromError = true;152 /**153 * Desrcibed the result of the check whether the registration was successful. If REGISTRATION_SUCCEEDED - we can continue recovery IF154 * REGISTRATION_FAILED - we can rollback IF CHECK_FAILED - we don't know and we have to try again.155 */156 protected RegistrationCheckResult registrationCheckResult =157 RegistrationCheckResult.REGISTRATION_SUCCEEDED;158 protected RecoveryResult recoveryResult = RecoveryResult.RECOVERY_SUCCEEDED;159 /**160 * if set to a value > 0, before calling the recovery the retryCount will be set to this value161 */162 protected int recoveryRertyCount = 0;163 /**164 * the timestamp of a recovery last try.165 */166 // gets initialized to some date in the past in the constructor167 protected Date recoveryLastTry;168 /**169 * if set to true, then the registration should do nothing170 */171 protected boolean nextTryInTheFuture = false;172 /**173 * If true - than during recovery store filesystem will become unavailable.174 */175 protected boolean shouldMakeFilesystemUnavailable = false;176 /**177 * If true than setting storage confirmed in application server will fail.178 */179 protected boolean shouldStorageConfirmationFail = false;180 /**181 * The behaviour on error. Default is that it should increase the try count.182 */183 protected boolean shouldIncrementTryCount = true;184 private RecoveryTestCase(String title)185 {186 this.title = title;187 this.overrideProperties = new HashMap<String, String>();188 this.overrideProperties.put("TEST_V2_API", "");189 // this the ultra-awkward way of initializing the recovery last try to some date in the190 // past191 Calendar c = Calendar.getInstance();192 c.set(2010, 1, 1);193 recoveryLastTry = c.getTime();194 }195 @Override196 public String toString()197 {198 return title;199 }200 }201 /*202 * The beginning of the basic testcase region203 */204 // INFO: basic testcase205 @Test(dataProvider = "recoveryTestCaseProvider")206 public void testBasicRecovery(final RecoveryTestCase testCase)207 {208 setUpHomeDataBaseExpectations();209 createData();210 Properties properties =211 createThreadPropertiesRelativeToScriptsFolder(testCase.dropboxScriptPath, null,212 testCase.overrideProperties);213 createHandler(properties, true, false);214 final RecordingMatcher<ch.systemsx.cisd.openbis.generic.shared.dto.AtomicEntityOperationDetails> atomicatOperationDetails =215 new RecordingMatcher<ch.systemsx.cisd.openbis.generic.shared.dto.AtomicEntityOperationDetails>();216 // create expectations217 context.checking(new BasicRecoveryTestExpectations(testCase, atomicatOperationDetails));218 handler.handle(markerFile);219 if (testCase.canRecoverFromError)220 {221 JythonHookTestTool.assertMessagesInWorkingDirectory(workingDirectory,222 "pre_metadata_registration");223 setTheRecoveryInfo(testCase.recoveryRertyCount, testCase.recoveryLastTry);224 assertRecoveryFile(testCase.recoveryRertyCount, RecoveryInfoDateConstraint.ORIGINAL,225 testCase.recoveryLastTry);226 assertOriginalMarkerFileExists();227 assertDirNotEmpty(precommitDirectory, "Precommit directory should not be empty");228 handler.handle(markerFile);229 if (testCase.nextTryInTheFuture)230 {231 assertRecoveryFile(testCase.recoveryRertyCount,232 RecoveryInfoDateConstraint.ORIGINAL, testCase.recoveryLastTry);233 assertOriginalMarkerFileExists();234 assertDirNotEmpty(precommitDirectory, "Precommit directory should not be empty");235 // nothing happened236 } else237 {238 assertPostRecoveryConstraints(testCase, atomicatOperationDetails);239 }240 } else241 {242 assertNoRecoveryTriggeredConstraints();243 }244 }245 class BasicRecoveryTestExpectations extends AbstractExpectations246 {247 final RecoveryTestCase testCase;248 public BasicRecoveryTestExpectations(final RecoveryTestCase testCase,249 final RecordingMatcher<AtomicEntityOperationDetails> atomicatOperationDetails)250 {251 super(atomicatOperationDetails);252 this.testCase = testCase;253 prepareExpecatations();254 }255 private void prepareExpecatations()256 {257 initialExpectations();258 registerDataSetsAndThrow(testCase.canRecoverFromError);259 // now registration has failed with the exception. we continue depending on where260 if (testCase.canRecoverFromError && false == testCase.nextTryInTheFuture)261 {262 checkRegistrationSucceeded();263 if (testCase.recoveryResult == RecoveryResult.RECOVERY_SUCCEEDED264 || testCase.recoveryResult == RecoveryResult.RETRY_AT_STORAGE_CONFIRMED_FAILURE)265 {266 setStorageConfirmed(testCase.shouldStorageConfirmationFail);267 }268 } else269 {270 // rollback271 }272 }273 protected void checkRegistrationSucceeded()274 {275 one(openBisService).didEntityOperationsSucceed(with(any(TechId.class)));276 switch (testCase.registrationCheckResult)277 {278 case REGISTRATION_SUCCEEDED:279 returnSuccessAndChangeEnvironment();280 break;281 case REGISTRATION_FAILED:282 will(returnValue(EntityOperationsState.NO_OPERATION));283 break;284 case CHECK_FAILED:285 will(throwException(new EnvironmentFailureException(286 "Cannot check whether the registration was successful")));287 break;288 case REGISTRATION_IN_PROGRESS:289 will(returnValue(EntityOperationsState.IN_PROGRESS));290 break;291 }292 }293 private void returnSuccessAndChangeEnvironment()294 {295 if (testCase.shouldMakeFilesystemUnavailable)296 {297 will(doAll(makeFileSystemUnavailableAction(),298 returnValue(EntityOperationsState.OPERATION_SUCCEEDED)));299 } else300 {301 will(returnValue(EntityOperationsState.OPERATION_SUCCEEDED));302 }303 }304 }305 private void assertNoRecoveryTriggeredConstraints()306 {307 assertDataSetNotStoredProcess(DATA_SET_CODE);308 assertNoOriginalMarkerFileExists();309 assertNoRecoveryMarkerFile();310 JythonHookTestTool.assertMessagesInWorkingDirectory(workingDirectory,311 "pre_metadata_registration", "rollback_pre_registration");312 assertDirEmptyOrContainsEmptyDirs(precommitDirectory);313 assertNoRecoveryMarkerFile();314 }315 private void assertPostRecoveryConstraints(316 final RecoveryTestCase testCase,317 final RecordingMatcher<ch.systemsx.cisd.openbis.generic.shared.dto.AtomicEntityOperationDetails> atomicatOperationDetails)318 {319 JythonHookTestTool jythonHookTestTool =320 JythonHookTestTool.createFromWorkingDirectory(workingDirectory);321 if (testCase.registrationCheckResult == RegistrationCheckResult.REGISTRATION_SUCCEEDED)322 {323 jythonHookTestTool.assertLogged("post_metadata_registration");324 }325 int expectedRetryCount =326 testCase.recoveryRertyCount + (testCase.shouldIncrementTryCount ? 1 : 0);327 switch (testCase.recoveryResult)328 {329 case RECOVERY_SUCCEEDED:330 // item in store331 assertStorageProcess(atomicatOperationDetails.recordedObject(), DATA_SET_CODE,332 "sub_data_set_1", 0);333 assertDirEmpty(precommitDirectory);334 assertNoOriginalMarkerFileExists();335 assertNoRecoveryMarkerFile();336 // the hooks after successful registration337 jythonHookTestTool.assertLogged("post_storage");338 break;339 case RECOVERY_ROLLED_BACK:340 assertDataSetNotStoredProcess(DATA_SET_CODE);341 assertDirEmptyOrContainsEmptyDirs(precommitDirectory);342 assertNoOriginalMarkerFileExists();343 assertNoRecoveryMarkerFile();344 jythonHookTestTool.assertLogged("rollback_pre_registration");345 break;346 case RETRY_AT_CANT_CHECK_REGISTRATION_STATUS:347 case RETRY_AT_STORAGE_FAILURE:348 assertDataSetNotStoredProcess(DATA_SET_CODE);349 if (false == testCase.shouldMakeFilesystemUnavailable)350 {351 assertDirNotEmpty(precommitDirectory, "Precommit directory should not be empty");352 }353 assertRecoveryFile(expectedRetryCount, RecoveryInfoDateConstraint.AFTER_ORIGINAL,354 testCase.recoveryLastTry);355 assertOriginalMarkerFileExists();356 break;357 case RETRY_AT_STORAGE_CONFIRMED_FAILURE:358 assertStorageProcess(atomicatOperationDetails.recordedObject(), DATA_SET_CODE,359 "sub_data_set_1", 0);360 assertRecoveryFile(expectedRetryCount, RecoveryInfoDateConstraint.AFTER_ORIGINAL,361 testCase.recoveryLastTry);362 assertOriginalMarkerFileExists();363 break;364 case GIVE_UP:365 assertDataSetNotStoredProcess(DATA_SET_CODE);366 assertNoOriginalMarkerFileExists();367 assertNoRecoveryMarkerFile();368 assertDirNotEmpty(precommitDirectory, "precommit should not be empty");369 break;370 }371 jythonHookTestTool.assertNoMoreMessages();372 }373 /**374 * Use this method to update the retry count in the recovery info file.375 */376 private void setTheRecoveryInfo(int count, Date lastTryDate)377 {378 File file = getCreatedRecoveryMarkerFile();379 DataSetStorageRecoveryInfo recoveryInfo =380 handler.getGlobalState().getStorageRecoveryManager()381 .getRecoveryFileFromMarker(file);382 // as the interface allow only increment, and not setting - we implement addition using383 // increment384 while (recoveryInfo.getTryCount() < count)385 {386 recoveryInfo.increaseTryCount();387 }388 recoveryInfo.setLastTry(lastTryDate);389 recoveryInfo.writeToFile(file);390 }391 private void assertDirNotEmpty(File file, String message)392 {393 assertFalse(message, 0 == file.list().length);394 }395 private void assertDirEmpty(File file)396 {397 String contents = file.getAbsolutePath();398 assertEquals(contents, "[]", Arrays.asList(file.list()).toString());399 }400 private void assertDirEmptyOrContainsEmptyDirs(File file)401 {402 for (String s : file.list())403 {404 File subFile = new File(file, s);405 if (subFile.isFile())406 {407 fail("Directory " + file + " is not empty! It contains a file" + s);408 } else if (subFile.isDirectory())409 {410 assertDirEmptyOrContainsEmptyDirs(subFile);411 }412 }413 }414 private void assertOriginalMarkerFileExists()415 {416 assertTrue(417 "The original registration marker file should not be deleted when entering recovery mode",418 markerFile.exists());419 }420 private void assertNoOriginalMarkerFileExists()421 {422 assertFalse("The original registration marker " + markerFile + " file should be deleted",423 markerFile.exists());424 }425 private enum RecoveryInfoDateConstraint426 {427 /**428 * the last try date is the one of the original recovery file429 */430 ORIGINAL,431 /**432 * the last try date is later then the original recovery file433 */434 AFTER_ORIGINAL435 }436 /**437 * @param tryCount - the excepted stored number of tries in a recovery file438 */439 private File assertRecoveryFile(int tryCount, RecoveryInfoDateConstraint dateConstraint,440 Date originalLastTryDate)441 {442 File file = getCreatedRecoveryMarkerFile();443 assertTrue("The recovery marker file does not exist! " + file, file.exists());444 DataSetStorageRecoveryInfo recoveryInfo =445 handler.getGlobalState().getStorageRecoveryManager()446 .getRecoveryFileFromMarker(file);447 File recoveryFile = recoveryInfo.getRecoveryStateFile();448 assertTrue("The recovery serialized file does not exist! " + recoveryFile,449 recoveryFile.exists());450 assertEquals("The try count in a recovery file is incorrect", tryCount,451 recoveryInfo.getTryCount());452 switch (dateConstraint)453 {454 case ORIGINAL:455 assertEquals(originalLastTryDate, recoveryInfo.getLastTry());456 break;457 case AFTER_ORIGINAL:458 assertTrue(459 "" + originalLastTryDate + " should be before " + recoveryInfo.getLastTry(),460 originalLastTryDate.before(recoveryInfo.getLastTry()));461 break;462 }463 return file;464 }465 private void assertNoRecoveryMarkerFile()466 {467 File file = getCreatedRecoveryMarkerFile();468 assertTrue("The recovery marker file should not exist! " + file, false == file.exists());469 }470 private File getCreatedRecoveryMarkerFile()471 {472 File originalIncoming =473 FileUtilities.removePrefixFromFileName(markerFile, FileConstants.IS_FINISHED_PREFIX);474 File recoveryMarkerFile =475 handler.getGlobalState().getStorageRecoveryManager()476 .getProcessingMarkerFile(originalIncoming);477 return recoveryMarkerFile;478 }479 // INFO: test with recovery when storage failed480 @Test481 public void testRecoveryFailureAtStorage()482 {483 RecoveryTestCase testCase = new RecoveryTestCase("No name");484 setUpHomeDataBaseExpectations();485 createData();486 Properties properties =487 createThreadPropertiesRelativeToScriptsFolder(testCase.dropboxScriptPath, null,488 testCase.overrideProperties);489 createHandler(properties, true, false);490 final RecordingMatcher<ch.systemsx.cisd.openbis.generic.shared.dto.AtomicEntityOperationDetails> atomicatOperationDetails =491 new RecordingMatcher<ch.systemsx.cisd.openbis.generic.shared.dto.AtomicEntityOperationDetails>();492 // create expectations493 context.checking(new StorageErrorExpectations(atomicatOperationDetails));494 handleAndMakeRecoverableImmediately(testCase);495 JythonHookTestTool.assertMessagesInWorkingDirectory(workingDirectory,496 "pre_metadata_registration", "post_metadata_registration");497 assertRecoveryFile(testCase.recoveryRertyCount, RecoveryInfoDateConstraint.ORIGINAL,498 testCase.recoveryLastTry);499 assertOriginalMarkerFileExists();500 makeFileSystemAvailable(workingDirectory);501 // this recovery should succeed502 handler.handle(markerFile);503 assertStorageProcess(atomicatOperationDetails.recordedObject(), DATA_SET_CODE,504 "sub_data_set_1", 0);505 assertNoOriginalMarkerFileExists();506 assertNoRecoveryMarkerFile();507 assertDirEmpty(precommitDirectory);508 //509 // // item in store510 //511 //512 JythonHookTestTool.assertMessagesInWorkingDirectory(workingDirectory, "post_storage");513 }514 class StorageErrorExpectations extends AbstractExpectations515 {516 public StorageErrorExpectations(517 final RecordingMatcher<AtomicEntityOperationDetails> atomicatOperationDetails)518 {519 super(atomicatOperationDetails);520 prepareExpecatations();521 }522 private void prepareExpecatations()523 {524 initialExpectations();525 registerDataSetsAndMakeFileSystemUnavailable();526 // the recovery should happen here527 setStorageConfirmed(false);528 }529 }530 // INFO: test with recovery from error in storage confirmed531 @Test532 public void testRecoveryFailureAtStorageConfirmed()533 {534 RecoveryTestCase testCase = new RecoveryTestCase("No name");535 setUpHomeDataBaseExpectations();536 createData();537 Properties properties =538 createThreadPropertiesRelativeToScriptsFolder(testCase.dropboxScriptPath, null,539 testCase.overrideProperties);540 createHandler(properties, true, false);541 final RecordingMatcher<ch.systemsx.cisd.openbis.generic.shared.dto.AtomicEntityOperationDetails> atomicatOperationDetails =542 new RecordingMatcher<ch.systemsx.cisd.openbis.generic.shared.dto.AtomicEntityOperationDetails>();543 // create expectations544 context.checking(new StorageConfirmedErrorExpectations(atomicatOperationDetails));545 handler.handle(markerFile);546 JythonHookTestTool.assertMessagesInWorkingDirectory(workingDirectory,547 "pre_metadata_registration", "post_metadata_registration");548 //549 // // item already in store550 //551 assertStorageProcess(atomicatOperationDetails.recordedObject(), DATA_SET_CODE,552 "sub_data_set_1", 0);553 setTheRecoveryInfo(testCase.recoveryRertyCount, testCase.recoveryLastTry);554 assertRecoveryFile(testCase.recoveryRertyCount, RecoveryInfoDateConstraint.ORIGINAL,555 testCase.recoveryLastTry);556 assertOriginalMarkerFileExists();557 // this recovery should succeed558 handler.handle(markerFile);559 assertNoOriginalMarkerFileExists();560 assertNoRecoveryMarkerFile();561 assertDirEmpty(precommitDirectory);562 JythonHookTestTool.assertMessagesInWorkingDirectory(workingDirectory, "post_storage");563 }564 class StorageConfirmedErrorExpectations extends AbstractExpectations565 {566 public StorageConfirmedErrorExpectations(567 final RecordingMatcher<AtomicEntityOperationDetails> atomicatOperationDetails)568 {569 super(atomicatOperationDetails);570 prepareExpecatations();571 }572 private void prepareExpecatations()573 {574 initialExpectations();575 registerDataSetsAndSucceed();576 setStorageConfirmed(true);577 // the recovery should happen here578 setStorageConfirmed(false);579 }580 }581 // INFO: the test that checks the retry mechanism582 @DataProvider(name = "retryDP")583 public Object[][] retryCounters()584 {585 return new Object[][]586 {587 { 1 },588 { 5 },589 { 15 } };590 }591 /**592 * This test tests that when the perform entity operation fails with the recoverable error, it will repeat the registration N times, and then593 * fail.594 */595 @Test(dataProvider = "retryDP")596 public void testRetryRegistrationNTimesAndFail(Integer retryCount)597 {598 RecoveryTestCase testCase = new RecoveryTestCase("No name");599 setUpHomeDataBaseExpectations();600 createData();601 Properties properties =602 createThreadPropertiesRelativeToScriptsFolder(testCase.dropboxScriptPath, null,603 testCase.overrideProperties);604 properties.setProperty(ThreadParameters.DATASET_REGISTRATION_MAX_RETRY_COUNT,605 retryCount.toString());606 properties.setProperty(ThreadParameters.DATASET_REGISTRATION_RETRY_PAUSE_IN_SEC, "0"); // 1s...

Full Screen

Full Screen

Source:AbstractExpectations.java Github

copy

Full Screen

...309 public void when(StatePredicate predicate) {310 currentBuilder().addOrderingConstraint(new InStateOrderingConstraint(predicate));311 }312 313 public void then(State state) {314 currentBuilder().addSideEffect(new ChangeStateSideEffect(state));315 }316 317 public void inSequence(Sequence sequence) {318 currentBuilder().addInSequenceOrderingConstraint(sequence);319 }320 public void inSequences(Sequence... sequences) {321 for (Sequence sequence : sequences) {322 inSequence(sequence);323 }324 }325}...

Full Screen

Full Screen

then

Using AI Code Generation

copy

Full Screen

1package org.jmock.test.acceptance;2import junit.framework.TestCase;3import org.jmock.Mock;4import org.jmock.core.Invocation;5import org.jmock.core.InvocationMatcher;6import org.jmock.core.Stub;7import org.jmock.core.constraint.IsEqual;8import org.jmock.core.constraint.IsInstanceOf;9import org.jmock.core.constraint.IsSame;10import org.jmock.core.constraint.IsTypeCompatible;11import org.jmock.core.constraint.IsAnything;12import org.jmock.core.constraint.IsCollectionContaining;13import org.jmock.core.constraint.IsIn;14import org.jmock.core.constraint.IsNot;15import org.jmock.core.constraint.IsNotSame;16import org.jmock.core.constraint.IsSameOrEqualTo;17import org.jmock.core.constraint.IsAnything;18import org.jmock.core.constraint.StringStartsWith;19import org.jmock.core.constraint.StringContains;20import org.jmock.core.constraint.StringEndsWith;21import org.jmock.core.constraint.StringMatches;22import org.jmock.core.constraint.StringDoesNotContain;23import org.jmock.core.constraint.StringDoesNotEndWith;24import org.jmock.core.constraint.StringDoesNotMatch;25import org.jmock.core.constraint.StringDoesNotStartWith;26import org.jmock.core.constraint.Matches;27import org.jmock.core.constraint.Is;28import org.jmock.core.constraint.IsEqual;29import org.jmock.core.constraint.IsNot;30import org.jmock.core.constraint.IsSame;31import org.jmock.core.constraint.IsNotSame;32import org.jmock.core.constraint.IsSameOrEqualTo;33import org.jmock.core.constraint.IsInstanceOf;34import org.jmock.core.constraint.IsCollectionContaining;35import org.jmock.core.constraint.IsIn;36import org.jmock.core.constraint.IsTypeCompatible;37import org.jmock.core.constraint.IsAnything;38import org.jmock.core.constraint.IsCollectionContaining;39import org.jmock.core.constraint.IsIn;40import org.jmock.core.constraint.IsNot;41import org.jmock.core.constraint.IsNotSame;42import org.jmock.core.constraint.IsSameOrEqualTo;43import org.jmock.core.constraint.IsInstanceOf;44import org.jmock.core.constraint.IsCollectionContaining;45import org.jmock.core.constraint.IsIn;46import org.jmock.core.constraint.IsTypeCompatible;47import org.jmock.core.constraint.IsAnything;48import org.jmock.core.constraint.IsCollectionContaining;49import org.jmock.core.constraint.IsIn;50import org.jmock.core.constraint.IsNot;51import org.jmock.core.constraint.IsNotSame;52import org.jmock.core.constraint.IsSameOrEqualTo;53import org.jmock.core.constraint.IsInstanceOf;

Full Screen

Full Screen

then

Using AI Code Generation

copy

Full Screen

1import java.util.*;2import org.jmock.*;3import org.jmock.core.*;4import org.jmock.core.constraint.*;5import org.jmock.core.matcher.*;6import org.jmock.util.*;7import org.jmock.core.stub.*;8import org.jmock.core.stub.ReturnStub;9import org.jmock.core.constraint.IsEqual;10public class 1 {11 public static void main(String args[]) {12 Mock mock = new Mock(Interface.class);13 Interface i = (Interface) mock.proxy();14 mock.expects(once()).method("method").with(eq("a")).will(returnValue("b"));15 i.method("a");16 mock.verify();17 }18}19import java.util.*;20import org.jmock.*;21import org.jmock.core.*;22import org.jmock.core.constraint.*;23import org.jmock.core.matcher.*;24import org.jmock.util.*;25import org.jmock.core.stub.*;26import org.jmock.core.stub.ReturnStub;27import org.jmock.core.constraint.IsEqual;28public class 2 {29 public static void main(String args[]) {30 Mock mock = new Mock(Interface.class);31 Interface i = (Interface) mock.proxy();32 mock.expects(once()).method("method").with(eq("a")).will(returnValue("b"));33 i.method("a");34 mock.verify();35 }36}37import java.util.*;38import org.jmock.*;39import org.jmock.core.*;40import org.jmock.core.constraint.*;41import org.jmock.core.matcher.*;42import org.jmock.util.*;43import org.jmock.core.stub.*;44import org.jmock.core.stub.ReturnStub;45import org.jmock.core.constraint.IsEqual;46public class 3 {47 public static void main(String args[]) {48 Mock mock = new Mock(Interface.class);49 Interface i = (Interface) mock.proxy();50 mock.expects(once()).method("method").with(eq("a")).will(returnValue("b"));51 i.method("a");

Full Screen

Full Screen

then

Using AI Code Generation

copy

Full Screen

1import org.jmock.Mockery;2import org.jmock.Expectations;3import org.jmock.integration.junit4.JUnit4Mockery;4import org.junit.Test;5import org.junit.runner.RunWith;6import org.jmock.integration.junit4.JMock;7import java.util.List;8@RunWith(JMock.class)9public class 1 {10 private Mockery context = new JUnit4Mockery();11 List mockList = context.mock(List.class);12 public void test() {13 context.checking(new Expectations() {14 {15 oneOf(mockList).add("one");16 oneOf(mockList).add("two");17 oneOf(mockList).add("three");18 }19 });20 mockList.add("one");21 mockList.add("two");22 mockList.add("three");23 }24}

Full Screen

Full Screen

then

Using AI Code Generation

copy

Full Screen

1import org.jmock.Mockery;2import org.jmock.Expectations;3import org.jmock.integration.junit4.JUnit4Mockery;4import org.junit.Test;5import org.junit.Before;6import org.junit.runner.RunWith;7import org.junit.runners.JUnit4;8public class Test1 {9 private Mockery context = new JUnit4Mockery();10 private Interface1 mockInterface1 = context.mock(Interface1.class);11 private Interface2 mockInterface2 = context.mock(Interface2.class);12 private Class1 class1;13 public void setUp() {14 class1 = new Class1(mockInterface1, mockInterface2);15 }16 public void test1() {17 context.checking(new Expectations() {{18 oneOf(mockInterface1).method1();19 will(returnValue(1));20 oneOf(mockInterface2).method2();21 will(returnValue(2));22 }});23 class1.method1();24 }25}26public interface Interface1 {27 public int method1();28}29public interface Interface2 {30 public int method2();31}32public class Class1 {33 private Interface1 interface1;34 private Interface2 interface2;35 public Class1(Interface1 interface1, Interface2 interface2) {36 this.interface1 = interface1;37 this.interface2 = interface2;38 }39 public void method1() {40 int i = interface1.method1();41 int j = interface2.method2();42 }43}44The problem is that you are not returning anything from method1() in your test class. The following code should work:45public void test1() {46 context.checking(new Expectations() {{47 oneOf(mockInterface1).method1();48 will(returnValue(1));49 oneOf(mockInterface2).method2();50 will(returnValue(2));51 }});52 class1.method1();

Full Screen

Full Screen

then

Using AI Code Generation

copy

Full Screen

1package org.jmock.examples;2import org.jmock.*;3import org.jmock.examples.calculator.*;4import org.jmock.lib.legacy.ClassImposteriser;5import junit.framework.TestCase;6public class CalculatorTest extends TestCase {7 private Mockery context = new Mockery() {{8 setImposteriser(ClassImposteriser.INSTANCE);9 }};10 private Calculator calculator = context.mock(Calculator.class);11 private Client client = new Client(calculator);12 public void testAddsNumbers() {13 context.checking(new Expectations() {{14 oneOf (calculator).add(2, 2); will(returnValue(4));15 }});16 assertEquals(4, client.add(2, 2));17 }18}19package org.jmock.examples.calculator;20public interface Calculator {21 int add(int a, int b);22 int subtract(int a, int b);23 int multiply(int a, int b);24 int divide(int a, int b);25}26package org.jmock.examples.calculator;27public class Client {28 private Calculator calculator;29 public Client(Calculator calculator) {30 this.calculator = calculator;31 }32 public int add(int a, int b) {33 return calculator.add(a, b);34 }35}36package org.jmock.examples;37import org.jmock.*;38import org.jmock.examples.calculator.*;39import org.jmock.lib.legacy.ClassImposteriser;40import junit.framework.TestCase;41public class CalculatorTest extends TestCase {42 private Mockery context = new Mockery() {{43 setImposteriser(ClassImposteriser.INSTANCE);44 }};45 private Calculator calculator = context.mock(Calculator.class);46 private Client client = new Client(calculator);47 public void testAddsNumbers() {48 context.checking(new Expectations() {{49 oneOf (calculator).add(2, 2); will(returnValue(4));50 }});51 assertEquals(4, client.add(2, 2));52 }53}54package org.jmock.examples.calculator;55public class CalculatorImpl implements Calculator {56 public int add(int a, int b) {57 return a + b;58 }59 public int subtract(int a, int b) {60 return a - b;61 }62 public int multiply(int a, int b) {63 return a * b;64 }

Full Screen

Full Screen

then

Using AI Code Generation

copy

Full Screen

1import org.jmock.Mockery;2import org.jmock.Expectations;3import org.jmock.Mockery;4import org.jmock.Expectations;5import org.jmock.integration.junit4.JUnit4Mockery;6import org.jmock.lib.legacy.ClassImposteriser;7import org.junit.Test;8public class Test1 {9 public void test() {10 Mockery context = new JUnit4Mockery();11 context.setImposteriser(ClassImposteriser.INSTANCE);12 final A mock = context.mock(A.class);13 context.checking(new Expectations() {14 {15 oneOf(mock).f();16 will(returnValue("hello"));17 }18 });19 System.out.println(mock.f());20 }21}22import org.jmock.Mockery;23import org.jmock.Expectations;24import org.jmock.Mockery;25import org.jmock.Expectations;26import org.junit.Test;27public class Test1 {28 public void test() {29 Mockery context = new Mockery();30 final A mock = context.mock(A.class);31 context.checking(new Expectations() {32 {33 oneOf(mock).f();34 will(returnValue("hello"));35 }36 });37 System.out.println(mock.f());38 }39}40public class A {41 public String f() {42 return "hello";43 }44}

Full Screen

Full Screen

then

Using AI Code Generation

copy

Full Screen

1import org.jmock.Mockery;2import org.jmock.Expectations;3import org.jmock.AbstractExpectations;4public class 1 {5 public static void main(String[] args) {6 Mockery context = new Mockery();7 final ITest mock = context.mock(ITest.class);8 context.checking(new Expectations() {{9 oneOf(mock).testMethod();10 will(AbstractExpectations.returnValue("Hello World!"));11 }});12 System.out.println(mock.testMethod());13 }14}15public interface ITest {16 public String testMethod();17}18public class ITestImpl implements ITest {19 public String testMethod() {20 return "Hello World!";21 }22}23public class Test {24 public static void main(String[] args) {25 ITest test = new ITestImpl();26 System.out.println(test.testMethod());27 }28}29Method Description returnValue(Object) Sets up an expectation that a method call on a mock object will return the specified value. returnValue(Object, String) Sets up an expectation that a method call on a mock object will return the specified value. returnValue(Object, String, Object[]) Sets up an expectation that a method call on a mock object will return the specified value. returnValue(Object, String, Object[], Type[]) Sets up an expectation that a method call on a mock object will return the specified value. returnValue(Object

Full Screen

Full Screen

then

Using AI Code Generation

copy

Full Screen

1import org.jmock.Mockery;2import org.jmock.Expectations;3import org.jmock.integration.junit4.JUnitRuleMockery;4import org.jmock.lib.legacy.ClassImposteriser;5import org.junit.Rule;6import org.junit.Test;7public class ExampleTest {8 public JUnitRuleMockery context = new JUnitRuleMockery() {9 {10 setImposteriser(ClassImposteriser.INSTANCE);11 }12 };13 public void test() {14 final Mockery mockery = context.mock(Mockery.class);15 context.then(new Expectations() {16 {17 oneOf(mockery).mockery();18 will(returnValue("mockery"));19 }20 });21 System.out.println(mockery.mockery());22 }23}

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful