Jmock Sequence Example Essay

Java Code Examples for org.jmock.Sequence

The following are top voted examples for showing how to use org.jmock.Sequence. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.

Example 1

Example 2

Example 3

Example 4

Example 5

Example 6

Example 7

Example 8

Example 9

Example 10

Example 11

Example 12

Example 13

Example 14

Example 15

Example 16

Example 17

Example 18

Example 19

Example 20

Example 21

Example 22

Example 23

Example 24

Example 25

Example 26

Example 27

Example 28

Example 29

Example 30

Example 31

Example 32

Example 33

Example 34

Example 35

Example 36

Example 37

Example 38

Example 39

Example 40

Example 41

Example 42

@Test public void testUpdateBookingsCorrectlyCallsTheManagers() throws Exception { // Test happy path for updateBookings: we verify the IPageManager // is asked to refresh all booking pages, and then the IBookingManager // is asked to delete the previous day's bookings. // ARRANGE final Sequence refreshSequence = mockery.sequence("refresh"); mockery.checking(new Expectations() { { oneOf(updateBookingsLambda.getPageManager(mockLogger)).refreshAllPages(with(validDates), with(apiGatewayBaseUrl), with(revvingSuffix)); inSequence(refreshSequence); oneOf(updateBookingsLambda.getBookingManager(mockLogger)).deleteYesterdaysBookings(false); inSequence(refreshSequence); } }); // ACT UpdateBookingsLambdaRequest request = new UpdateBookingsLambdaRequest(); updateBookingsLambda.updateBookings(request, mockContext); }
@Test public void happyCase() throws Exception { final String someName = "Foobar"; // given final Sequence seq = context.sequence("create"); context.checking(new Expectations() { { oneOf(mockServiceRegistry).injectServicesInto(with(any(SimpleObject.class))); inSequence(seq); oneOf(mockRepositoryService).persist(with(nameOf(someName))); inSequence(seq); } }); // when final SimpleObject obj = simpleObjectRepository.create(someName); // then assertThat(obj).isNotNull(); assertThat(obj.getName()).isEqualTo(someName); }
@Test public void testGetSafeParameterString() { final HttpServletRequest request = context.mock(HttpServletRequest.class); context.checking(new Expectations() { { Sequence getParams = new NamedSequence("getParams"); for (Map.Entry<String, String> entry : stringParams.entrySet()) { oneOf(request).getParameter(entry.getKey()); inSequence(getParams); will(returnValue(entry.getValue())); } } }); String value = ServletUtils.getSafeParameter(request, "param1", "default"); assertThat("value1", equalTo(value)); value = ServletUtils.getSafeParameter(request, "param2", "default"); assertThat("value2", equalTo(value)); value = ServletUtils.getSafeParameter(request, "param3", "default"); assertThat("default", equalTo(value)); }
@Test public void testGetSafeParameterInt() { final HttpServletRequest request = context.mock(HttpServletRequest.class); context.checking(new Expectations() { { Sequence getParams = new NamedSequence("getParams"); for (Map.Entry<String, String> entry : intParams.entrySet()) { oneOf(request).getParameter(entry.getKey()); inSequence(getParams); will(returnValue(entry.getValue())); } } }); int value = ServletUtils.getSafeParameter(request, "param1", 0); assertEquals(1, value); value = ServletUtils.getSafeParameter(request, "param2", 0); assertEquals(2, value); value = ServletUtils.getSafeParameter(request, "param3", 0); assertEquals(0, value); }
@Test public void happyCase() throws Exception { // given final QuickObject quickObject = new QuickObject(); final Sequence seq = context.sequence("create"); context.checking(new Expectations() { { oneOf(mockContainer).newTransientInstance(QuickObject.class); inSequence(seq); will(returnValue(quickObject)); oneOf(mockContainer).persistIfNotAlready(quickObject); inSequence(seq); } }); // when final QuickObject obj = quickObjectRepository.create("Foobar"); // then assertThat(obj).isEqualTo(quickObject); assertThat(obj.getName()).isEqualTo("Foobar"); }
@Test public void testSetStatus() { final Sequence setSequence = context.sequence("setSequence"); final Sequence getSequence = context.sequence("getSequence"); context.checking(new Expectations() {{ oneOf (textComponent).setText("First Status\n"); inSequence(setSequence); oneOf (textComponent).setText("First Status\nSecond Status\n"); inSequence(setSequence); oneOf (textComponent).getText(); inSequence(getSequence); will(returnValue("")); oneOf (textComponent).getText(); inSequence(getSequence); will(returnValue("First Status\n")); oneOf (textComponent).getText(); inSequence(getSequence); will(returnValue("First Status\n")); oneOf (textComponent).getText(); inSequence(getSequence); will(returnValue("First Status\nSecondStatus\n")); }}); progressListener.setStatus("First Status"); assertEquals("First Status", progressListener.getStatus()); progressListener.setStatus("Second Status"); assertEquals("Second Status", progressListener.getStatus()); }
@Test public void happyCase() throws Exception { // given final SimpleObject simpleObject = new SimpleObject(); final Sequence seq = context.sequence("create"); context.checking(new Expectations() { { oneOf(mockContainer).newTransientInstance(SimpleObject.class); inSequence(seq); will(returnValue(simpleObject)); oneOf(mockContainer).persistIfNotAlready(simpleObject); inSequence(seq); } }); // when final SimpleObject obj = simpleObjects.create("Foobar"); // then assertThat(obj).isEqualTo(simpleObject); assertThat(obj.getName()).isEqualTo("Foobar"); }
@Test public void testThatDisposeUnsetsTheActiveStatusAndStopsTheDiscoveryService() { final DiscoveryService discoveryService = context.mock(DiscoveryService.class); final Sequence seq = context.sequence("StartStopSequence"); context.checking(new Expectations() {{ atMost(1).of(discoveryServiceFactory).createDiscoveryService(peerProvider, discoveryServiceConfig); inSequence(seq); atMost(1).of(discoveryService).startDiscoveryService(); inSequence(seq); atMost(1).of(discoveryService).stopDiscoveryService(); inSequence(seq); }}); peerProvider.init(); Assert.assertTrue(peerProvider.isActive()); peerProvider.dispose(); Assert.assertFalse(peerProvider.isActive()); }
@Test public void happyCase() throws Exception { // given final Owner owner = new Owner(); final Sequence seq = context.sequence("create"); context.checking(new Expectations() { { oneOf(mockContainer).newTransientInstance(Owner.class); inSequence(seq); will(returnValue(owner)); oneOf(mockContainer).persistIfNotAlready(owner); inSequence(seq); } }); // when final Owner obj = owners.create("George"); // then assertThat(obj, is(owner)); assertThat(obj.getName(), is("George")); }
@Test public void testGetSafeParameterString() { final HttpServletRequest request = context.mock(HttpServletRequest.class); context.checking(new Expectations() { { Sequence getParams = new NamedSequence("getParams"); for (Map.Entry<String, String> entry : stringParams.entrySet()) { oneOf(request).getParameter(entry.getKey()); inSequence(getParams); will(returnValue(entry.getValue())); } } }); String value = ServletUtils.getSafeParameter(request, "param1", "default"); assertThat("value1", equalTo(value)); value = ServletUtils.getSafeParameter(request, "param2", "default"); assertThat("value2", equalTo(value)); value = ServletUtils.getSafeParameter(request, "param3", "default"); assertThat("default", equalTo(value)); }
@Test public void testGetSafeParameterInt() { final HttpServletRequest request = context.mock(HttpServletRequest.class); context.checking(new Expectations() { { Sequence getParams = new NamedSequence("getParams"); for (Map.Entry<String, String> entry : intParams.entrySet()) { oneOf(request).getParameter(entry.getKey()); inSequence(getParams); will(returnValue(entry.getValue())); } } }); int value = ServletUtils.getSafeParameter(request, "param1", 0); assertEquals(1, value); value = ServletUtils.getSafeParameter(request, "param2", 0); assertEquals(2, value); value = ServletUtils.getSafeParameter(request, "param3", 0); assertEquals(0, value); }
@Test public void happyCase() throws Exception { // given final Owner owner = new Owner(); final Sequence seq = context.sequence("create"); context.checking(new Expectations() { { oneOf(mockContainer).newTransientInstance(Owner.class); inSequence(seq); will(returnValue(owner)); oneOf(mockContainer).persistIfNotAlready(owner); inSequence(seq); } }); // when final Owner obj = owners.create("George"); // then assertThat(obj, is(owner)); assertThat(obj.getName(), is("George")); }
@Test public void testEmptyStateGeneratesNewLock() throws Exception { final Sequence callSeq = jmock.sequence("call-seq"); jmock.checking(new Expectations() {{ // oneOf(readLock).lock();inSequence(callSeq); oneOf(mapStoredState).get();will(returnValue(null));inSequence(callSeq); oneOf(boundLockFactory).newInstance();will(returnValue(factoryGeneratedState));inSequence(callSeq); oneOf(mapStoredState).compareAndSet(null, factoryGeneratedState);will(returnValue(true));inSequence(callSeq); // oneOf(readLock).unlock();inSequence(callSeq); oneOf(factoryGeneratedState).sharedLock(with(aNull(LockClient.class)),with(any(String.class)));inSequence(callSeq); }}); constructedLock.readLock().lock(); }
@Test public void testReadLock() throws Exception { final Sequence callSeq = jmock.sequence("call-seq"); jmock.checking(new Expectations() {{ // oneOf(readLock).lock();inSequence(callSeq); oneOf(mapStoredState).get();will(returnValue(factoryGeneratedState));inSequence(callSeq); // oneOf(readLock).unlock();inSequence(callSeq); oneOf(factoryGeneratedState).sharedLock(with(aNull(LockClient.class)),with(any(String.class)));inSequence(callSeq); }}); constructedLock.readLock().lock(); jmock.checking(new Expectations() {{ // oneOf(readLock).lock();inSequence(callSeq); oneOf(mapStoredState).get();will(returnValue(factoryGeneratedState));inSequence(callSeq); // oneOf(readLock).unlock();inSequence(callSeq); oneOf(factoryGeneratedState).sharedUnlock(with(aNull(LockClient.class)),with(any(String.class)));inSequence(callSeq); }}); constructedLock.readLock().unlock(); }
@Test public void testWriteLock() throws Exception { final Sequence callSeq = jmock.sequence("call-seq"); jmock.checking(new Expectations() {{ // oneOf(readLock).lock();inSequence(callSeq); oneOf(mapStoredState).get();will(returnValue(factoryGeneratedState));inSequence(callSeq); // oneOf(readLock).unlock();inSequence(callSeq); oneOf(factoryGeneratedState).exclusiveLock(with(aNull(LockClient.class)),with(any(String.class)));inSequence(callSeq); }}); constructedLock.writeLock().lock(); jmock.checking(new Expectations() {{ // oneOf(readLock).lock();inSequence(callSeq); oneOf(mapStoredState).get();will(returnValue(factoryGeneratedState));inSequence(callSeq); // oneOf(readLock).unlock();inSequence(callSeq); oneOf(factoryGeneratedState).exclusiveUnlock(with(aNull(LockClient.class)),with(any(String.class))); inSequence(callSeq); }}); constructedLock.writeLock().unlock(); }
@Test public void testOnMessage() throws Exception { final Sequence callSeq = jmock.sequence("call-seq"); final IntentEntry entry = new IntentEntry(InetSocketAddress.createUnresolved("localhost",1111),LockMode.EXCLUSIVE,15L,15L); final ClusterLockManager.MultiplexedLockMessage multiplexedMessage = new ClusterLockManager.MultiplexedLockMessage(lockName,entry); jmock.checking(new Expectations() {{ oneOf(currentLocks).binding(lockName);will(returnValue(mapStoredState));inSequence(callSeq); oneOf(lockFactoryBinder).createFactory(lockName);will(returnValue(boundLockFactory));inSequence(callSeq); oneOf(clusterMembershipLock).readLock();will(returnValue(readLock));inSequence(callSeq); // oneOf(readLock).lock();inSequence(callSeq); oneOf(mapStoredState).get();will(returnValue(factoryGeneratedState));inSequence(callSeq); // oneOf(readLock).unlock();inSequence(callSeq); oneOf(factoryGeneratedState).onMessage(entry);inSequence(callSeq); }}); mgr.onMessage(multiplexedMessage); }
@Test public void andConditions() throws Exception{ Method m = createMethodForTesting(Object.class, "getPersonByNameAndAge", String.class, int.class); QueryInfo qi = parser.parse(m); final QueryVisitor visitorMock = context.mock(QueryVisitor.class); context.checking(new Expectations() {{ Sequence sequence = context.sequence("query sequence"); one(visitorMock).visitEntity("Person");inSequence(sequence); one(visitorMock).visitCondition("name", ComparisonType.EQUALS);inSequence(sequence); one(visitorMock).visitConector("and");inSequence(sequence); one(visitorMock).visitCondition("age", ComparisonType.EQUALS);inSequence(sequence); one(visitorMock).visitEnd(); inSequence(sequence); }}); qi.visit(visitorMock); }
@Test public void orConditions() throws Exception{ Method m = createMethodForTesting(Object.class, "getPersonByNameOrAge", String.class, int.class); QueryInfo qi = parser.parse(m); final QueryVisitor visitorMock = context.mock(QueryVisitor.class); context.checking(new Expectations() {{ Sequence sequence = context.sequence("query sequence"); one(visitorMock).visitEntity("Person");inSequence(sequence); one(visitorMock).visitCondition("name", ComparisonType.EQUALS);inSequence(sequence); one(visitorMock).visitConector("or");inSequence(sequence); one(visitorMock).visitCondition("age", ComparisonType.EQUALS);inSequence(sequence); one(visitorMock).visitEnd(); inSequence(sequence); }}); qi.visit(visitorMock); }
@Test public void andOrConditions() throws Exception{ Method m = createMethodForTesting(Object.class, "getPersonByNameOrLastNameAndAge", String.class, String.class, int.class); QueryInfo qi = parser.parse(m); final QueryVisitor visitorMock = context.mock(QueryVisitor.class); context.checking(new Expectations() {{ Sequence sequence = context.sequence("query sequence"); one(visitorMock).visitEntity("Person");inSequence(sequence); one(visitorMock).visitCondition("name", ComparisonType.EQUALS);inSequence(sequence); one(visitorMock).visitConector("or");inSequence(sequence); one(visitorMock).visitCondition("lastName", ComparisonType.EQUALS);inSequence(sequence); one(visitorMock).visitConector("and");inSequence(sequence); one(visitorMock).visitCondition("age", ComparisonType.EQUALS);inSequence(sequence); one(visitorMock).visitEnd(); inSequence(sequence); }}); qi.visit(visitorMock); }
private void executeConditionTypesWithMethodNamed(String methodName,final ComparisonType expectedType, int mockNumber, Class parameterType, final String property) throws NoSuchMethodException { mockClass = new ClassMock("ExampleInterface", true); Method m = createMethodForTesting(Object.class, methodName, parameterType); QueryInfo qi = parser.parse(m); final QueryVisitor visitorMock = context.mock(QueryVisitor.class,"QueryVisitor"+mockNumber); context.checking(new Expectations() {{ Sequence sequence = context.sequence("query sequence"); one(visitorMock).visitEntity("Person");inSequence(sequence); one(visitorMock).visitCondition(property, expectedType);inSequence(sequence); one(visitorMock).visitEnd(); inSequence(sequence); }}); qi.visit(visitorMock); }
@Test public void andOrConditionsWithOperators() throws Exception{ Method m = createMethodForTesting(Object.class, "getPersonByNameGreaterOrLastNameNotEqualsAndAgeLesserOrEquals", String.class, String.class, int.class); QueryInfo qi = parser.parse(m); final QueryVisitor visitorMock = context.mock(QueryVisitor.class); context.checking(new Expectations() {{ Sequence sequence = context.sequence("query sequence"); one(visitorMock).visitEntity("Person");inSequence(sequence); one(visitorMock).visitCondition("name", ComparisonType.GREATER);inSequence(sequence); one(visitorMock).visitConector("or");inSequence(sequence); one(visitorMock).visitCondition("lastName", ComparisonType.NOT_EQUALS);inSequence(sequence); one(visitorMock).visitConector("and");inSequence(sequence); one(visitorMock).visitCondition("age", ComparisonType.LESSER_OR_EQUALS);inSequence(sequence); one(visitorMock).visitEnd(); inSequence(sequence); }}); qi.visit(visitorMock); }
@Test public void simpleDomainTerm() throws Exception{ Annotation an = domainTermWithOneCondition("manager","job", "MAN", ComparisonType.EQUALS); mockClass.addAnnotation(an); Method m = createMethodForTesting(Object.class, "getPersonManager"); QueryInfo qi = parser.parse(m); final QueryVisitor visitorMock = context.mock(QueryVisitor.class); context.checking(new Expectations() {{ Sequence sequence = context.sequence("query sequence"); one(visitorMock).visitEntity("Person");inSequence(sequence); one(visitorMock).visitCondition("job", ComparisonType.EQUALS, "MAN");inSequence(sequence); one(visitorMock).visitEnd(); inSequence(sequence); }}); qi.visit(visitorMock); }
@Test public void compositeDomainTerm() throws Exception{ Annotation an = domainTermWithOneCondition("super manager","job", "SUPMAN", ComparisonType.EQUALS); mockClass.addAnnotation(an); Method m = createMethodForTesting(Object.class, "getPersonSuperManager"); QueryInfo qi = parser.parse(m); final QueryVisitor visitorMock = context.mock(QueryVisitor.class); context.checking(new Expectations() {{ Sequence sequence = context.sequence("query sequence"); one(visitorMock).visitEntity("Person");inSequence(sequence); one(visitorMock).visitCondition("job", ComparisonType.EQUALS, "SUPMAN");inSequence(sequence); one(visitorMock).visitEnd(); inSequence(sequence); }}); qi.visit(visitorMock); }
@Test public void moreThanOneDomainTerm() throws Exception{ Annotation an1 = domainTermWithOneCondition("super manager","job", "SUPMAN", ComparisonType.EQUALS); Annotation an2 = domainTermWithOneCondition("manager","job", "MAN", ComparisonType.EQUALS); Annotation an = new Annotation(DomainTerms.class, new Annotation[]{an1,an2}); mockClass.addAnnotation(an); Method m = createMethodForTesting(Object.class, "getPersonManager"); QueryInfo qi = parser.parse(m); final QueryVisitor visitorMock = context.mock(QueryVisitor.class); context.checking(new Expectations() {{ Sequence sequence = context.sequence("query sequence"); one(visitorMock).visitEntity("Person");inSequence(sequence); one(visitorMock).visitCondition("job", ComparisonType.EQUALS, "MAN");inSequence(sequence); one(visitorMock).visitEnd(); inSequence(sequence); }}); qi.visit(visitorMock); }
@Test public void domainTermWithTwoConditions() throws Exception{ Annotation an = domainTermWithOneCondition("super manager","job", "SUPMAN", ComparisonType.EQUALS); Annotation t = createDomainTerm("manager"); Annotation c1 = createCondition("job", "MAN", ComparisonType.EQUALS); Annotation c2 = createCondition("lastName", "S", ComparisonType.STARTS); t.addProperty("conditions", new Annotation[]{c1,c2}); mockClass.addAnnotation(t); Method m = createMethodForTesting(Object.class, "getPersonManager"); QueryInfo qi = parser.parse(m); final QueryVisitor visitorMock = context.mock(QueryVisitor.class); context.checking(new Expectations() {{ Sequence sequence = context.sequence("query sequence"); one(visitorMock).visitEntity("Person");inSequence(sequence); one(visitorMock).visitCondition("job", ComparisonType.EQUALS, "MAN");inSequence(sequence); one(visitorMock).visitConector("and");inSequence(sequence); one(visitorMock).visitCondition("lastName", ComparisonType.STARTS, "S");inSequence(sequence); one(visitorMock).visitEnd(); inSequence(sequence); }}); qi.visit(visitorMock); }
@Test public void domainTermWithCondition() throws Exception{ Annotation an = domainTermWithOneCondition("manager","job", "MAN", ComparisonType.EQUALS); mockClass.addAnnotation(an); Method m = createMethodForTesting(Object.class, "getPersonManagerByAgeGreater", int.class); QueryInfo qi = parser.parse(m); final QueryVisitor visitorMock = context.mock(QueryVisitor.class); context.checking(new Expectations() {{ Sequence sequence = context.sequence("query sequence"); one(visitorMock).visitEntity("Person");inSequence(sequence); one(visitorMock).visitCondition("job", ComparisonType.EQUALS, "MAN");inSequence(sequence); one(visitorMock).visitConector("and");inSequence(sequence); one(visitorMock).visitCondition("age", ComparisonType.GREATER);inSequence(sequence); one(visitorMock).visitEnd(); inSequence(sequence); }}); assertEquals("Only the variable parameter should be listed",1,qi.getNamedParemeters().size()); qi.visit(visitorMock); }
@Test public void domainTermWithInt() throws Exception{ Annotation an = domainTermWithOneCondition("underage","age", "18", ComparisonType.LESSER); mockClass.addAnnotation(an); Method m = createMethodForTesting(Object.class, "getPersonUnderage"); QueryInfo qi = parser.parse(m); final QueryVisitor visitorMock = context.mock(QueryVisitor.class); context.checking(new Expectations() {{ Sequence sequence = context.sequence("query sequence"); one(visitorMock).visitEntity("Person");inSequence(sequence); one(visitorMock).visitCondition("age", ComparisonType.LESSER, 18);inSequence(sequence); one(visitorMock).visitEnd(); inSequence(sequence); }}); qi.visit(visitorMock); }
@Test public void orderByWithParameter() throws Exception{ Method m = createMethodForTesting(Object.class, "getPersonByLastNameOrderByName", String.class); QueryInfo qi = parser.parse(m); final QueryVisitor visitorMock = context.mock(QueryVisitor.class); context.checking(new Expectations() {{ Sequence sequence = context.sequence("query sequence"); one(visitorMock).visitEntity("Person");inSequence(sequence); one(visitorMock).visitCondition("lastName", ComparisonType.EQUALS);inSequence(sequence); one(visitorMock).visitOrderBy("name", OrderingDirection.ASC);inSequence(sequence); one(visitorMock).visitEnd(); inSequence(sequence); }}); qi.visit(visitorMock); }
@Test public void orderByWithAnd() throws Exception{ Method m = createMethodForTesting(Object.class, "getPersonByLastNameOrderByNameAndAgeDesc", String.class); QueryInfo qi = parser.parse(m); final QueryVisitor visitorMock = context.mock(QueryVisitor.class); context.checking(new Expectations() {{ Sequence sequence = context.sequence("query sequence"); one(visitorMock).visitEntity("Person");inSequence(sequence); one(visitorMock).visitCondition("lastName", ComparisonType.EQUALS);inSequence(sequence); one(visitorMock).visitOrderBy("name", OrderingDirection.ASC);inSequence(sequence); one(visitorMock).visitOrderBy("age", OrderingDirection.DESC);inSequence(sequence); one(visitorMock).visitEnd(); inSequence(sequence); }}); qi.visit(visitorMock); }
@Test public void compareToNull() throws NoSuchMethodException { mockClass = new ClassMock("ExampleInterface", true); Method m = createMethodWithAnnotationForTesting(Object.class, "getPersonByNameContains", CompareToNull.class, String.class); QueryInfo qi = parser.parse(m); final QueryVisitor visitorMock = context.mock(QueryVisitor.class); context.checking(new Expectations() {{ Sequence sequence = context.sequence("query sequence"); one(visitorMock).visitEntity("Person");inSequence(sequence); one(visitorMock).visitCondition("name", ComparisonType.CONTAINS, NullOption.COMPARE_TO_NULL);inSequence(sequence); one(visitorMock).visitEnd(); inSequence(sequence); }}); qi.visit(visitorMock); }
@Test public void ignoreWhenNull() throws NoSuchMethodException { mockClass = new ClassMock("ExampleInterface", true); Method m = createMethodWithAnnotationForTesting(Object.class, "getPersonByNameAndAge", IgnoreWhenNull.class, String.class, int.class); QueryInfo qi = parser.parse(m); final QueryVisitor visitorMock = context.mock(QueryVisitor.class); context.checking(new Expectations() {{ Sequence sequence = context.sequence("query sequence"); one(visitorMock).visitEntity("Person");inSequence(sequence); one(visitorMock).visitCondition("name", ComparisonType.EQUALS, NullOption.IGNORE_WHEN_NULL);inSequence(sequence); one(visitorMock).visitConector("and");inSequence(sequence); one(visitorMock).visitCondition("age", ComparisonType.EQUALS);inSequence(sequence); one(visitorMock).visitEnd(); inSequence(sequence); }}); qi.visit(visitorMock); }
@Test public void queryWithOneRegularProperty() throws Exception{ queryMockClass.addProperty("name", String.class); queryClass = queryMockClass.createClass(); Method m = createMethodWithAnnotationForTesting(Person.class, "getPerson", QueryObject.class, queryClass); QueryInfo qi = parser.parse(m); final QueryVisitor visitorMock = context.mock(QueryVisitor.class); context.checking(new Expectations() {{ Sequence sequence = context.sequence("query sequence"); one(visitorMock).visitEntity("Person");inSequence(sequence); one(visitorMock).visitCondition("name", ComparisonType.EQUALS);inSequence(sequence); one(visitorMock).visitEnd(); inSequence(sequence); }}); qi.visit(visitorMock); }
@Test public void queryWithOneRegularMethod() throws Exception{ queryMockClass.addMethod(String.class, "getName"); queryClass = queryMockClass.createClass(); Method m = createMethodWithAnnotationForTesting(Person.class, "getPerson", QueryObject.class, queryClass); QueryInfo qi = parser.parse(m); final QueryVisitor visitorMock = context.mock(QueryVisitor.class); context.checking(new Expectations() {{ Sequence sequence = context.sequence("query sequence"); one(visitorMock).visitEntity("Person");inSequence(sequence); one(visitorMock).visitCondition("name", ComparisonType.EQUALS);inSequence(sequence); one(visitorMock).visitEnd(); inSequence(sequence); }}); qi.visit(visitorMock); }
@Test public void andConditions() throws Exception{ Method m = createMethodForTesting(Object.class, "getPersonByNameAndAge", String.class, int.class); QueryInfo qi = parser.parse(m); final QueryVisitor visitorMock = context.mock(QueryVisitor.class); context.checking(new Expectations() {{ Sequence sequence = context.sequence("query sequence"); one(visitorMock).visitEntity("Person");inSequence(sequence); one(visitorMock).visitCondition("name", ComparisonType.EQUALS);inSequence(sequence); one(visitorMock).visitConector("and");inSequence(sequence); one(visitorMock).visitCondition("age", ComparisonType.EQUALS);inSequence(sequence); one(visitorMock).visitEnd(); inSequence(sequence); }}); qi.visit(visitorMock); }
@Test public void orConditions() throws Exception{ Method m = createMethodForTesting(Object.class, "getPersonByNameOrAge", String.class, int.class); QueryInfo qi = parser.parse(m); final QueryVisitor visitorMock = context.mock(QueryVisitor.class); context.checking(new Expectations() {{ Sequence sequence = context.sequence("query sequence"); one(visitorMock).visitEntity("Person");inSequence(sequence); one(visitorMock).visitCondition("name", ComparisonType.EQUALS);inSequence(sequence); one(visitorMock).visitConector("or");inSequence(sequence); one(visitorMock).visitCondition("age", ComparisonType.EQUALS);inSequence(sequence); one(visitorMock).visitEnd(); inSequence(sequence); }}); qi.visit(visitorMock); }
@Test public void andOrConditions() throws Exception{ Method m = createMethodForTesting(Object.class, "getPersonByNameOrLastNameAndAge", String.class, String.class, int.class); QueryInfo qi = parser.parse(m); final QueryVisitor visitorMock = context.mock(QueryVisitor.class); context.checking(new Expectations() {{ Sequence sequence = context.sequence("query sequence"); one(visitorMock).visitEntity("Person");inSequence(sequence); one(visitorMock).visitCondition("name", ComparisonType.EQUALS);inSequence(sequence); one(visitorMock).visitConector("or");inSequence(sequence); one(visitorMock).visitCondition("lastName", ComparisonType.EQUALS);inSequence(sequence); one(visitorMock).visitConector("and");inSequence(sequence); one(visitorMock).visitCondition("age", ComparisonType.EQUALS);inSequence(sequence); one(visitorMock).visitEnd(); inSequence(sequence); }}); qi.visit(visitorMock); }
@Test public void andOrConditionsWithOperators() throws Exception{ Method m = createMethodForTesting(Object.class, "getPersonByNameGreaterOrLastNameNotEqualsAndAgeLesserOrEquals", String.class, String.class, int.class); QueryInfo qi = parser.parse(m); final QueryVisitor visitorMock = context.mock(QueryVisitor.class); context.checking(new Expectations() {{ Sequence sequence = context.sequence("query sequence"); one(visitorMock).visitEntity("Person");inSequence(sequence); one(visitorMock).visitCondition("name", ComparisonType.GREATER);inSequence(sequence); one(visitorMock).visitConector("or");inSequence(sequence); one(visitorMock).visitCondition("lastName", ComparisonType.NOT_EQUALS);inSequence(sequence); one(visitorMock).visitConector("and");inSequence(sequence); one(visitorMock).visitCondition("age", ComparisonType.LESSER_OR_EQUALS);inSequence(sequence); one(visitorMock).visitEnd(); inSequence(sequence); }}); qi.visit(visitorMock); }
@Test public void simpleDomainTerm() throws Exception{ Annotation an = domainTermWithOneCondition("manager","job", "MAN", ComparisonType.EQUALS); mockClass.addAnnotation(an); Method m = createMethodForTesting(Object.class, "getPersonManager"); QueryInfo qi = parser.parse(m); final QueryVisitor visitorMock = context.mock(QueryVisitor.class); context.checking(new Expectations() {{ Sequence sequence = context.sequence("query sequence"); one(visitorMock).visitEntity("Person");inSequence(sequence); one(visitorMock).visitCondition("job", ComparisonType.EQUALS, "MAN");inSequence(sequence); one(visitorMock).visitEnd(); inSequence(sequence); }}); qi.visit(visitorMock); }
@Test public void compositeDomainTerm() throws Exception{ Annotation an = domainTermWithOneCondition("super manager","job", "SUPMAN", ComparisonType.EQUALS); mockClass.addAnnotation(an); Method m = createMethodForTesting(Object.class, "getPersonSuperManager"); QueryInfo qi = parser.parse(m); final QueryVisitor visitorMock = context.mock(QueryVisitor.class); context.checking(new Expectations() {{ Sequence sequence = context.sequence("query sequence"); one(visitorMock).visitEntity("Person");inSequence(sequence); one(visitorMock).visitCondition("job", ComparisonType.EQUALS, "SUPMAN");inSequence(sequence); one(visitorMock).visitEnd(); inSequence(sequence); }}); qi.visit(visitorMock); }
@Test public void moreThanOneDomainTerm() throws Exception{ Annotation an1 = domainTermWithOneCondition("super manager","job", "SUPMAN", ComparisonType.EQUALS); Annotation an2 = domainTermWithOneCondition("manager","job", "MAN", ComparisonType.EQUALS); Annotation an = new Annotation(DomainTerms.class, new Annotation[]{an1,an2}); mockClass.addAnnotation(an); Method m = createMethodForTesting(Object.class, "getPersonManager"); QueryInfo qi = parser.parse(m); final QueryVisitor visitorMock = context.mock(QueryVisitor.class); context.checking(new Expectations() {{ Sequence sequence = context.sequence("query sequence"); one(visitorMock).visitEntity("Person");inSequence(sequence); one(visitorMock).visitCondition("job", ComparisonType.EQUALS, "MAN");inSequence(sequence); one(visitorMock).visitEnd(); inSequence(sequence); }}); qi.visit(visitorMock); }
@Test public void domainTermWithTwoConditions() throws Exception{ Annotation an = domainTermWithOneCondition("super manager","job", "SUPMAN", ComparisonType.EQUALS); Annotation t = createDomainTerm("manager"); Annotation c1 = createCondition("job", "MAN", ComparisonType.EQUALS); Annotation c2 = createCondition("lastName", "S", ComparisonType.STARTS); t.addProperty("conditions", new Annotation[]{c1,c2}); mockClass.addAnnotation(t); Method m = createMethodForTesting(Object.class, "getPersonManager"); QueryInfo qi = parser.parse(m); final QueryVisitor visitorMock = context.mock(QueryVisitor.class); context.checking(new Expectations() {{ Sequence sequence = context.sequence("query sequence"); one(visitorMock).visitEntity("Person");inSequence(sequence); one(visitorMock).visitCondition("job", ComparisonType.EQUALS, "MAN");inSequence(sequence); one(visitorMock).visitConector("and");inSequence(sequence); one(visitorMock).visitCondition("lastName", ComparisonType.STARTS, "S");inSequence(sequence); one(visitorMock).visitEnd(); inSequence(sequence); }}); qi.visit(visitorMock); }

jMock 2 Cheat Sheet

Test Fixture Class

Show for: JUnit 3JUnit 4Other

Raw

import org.jmock.Mockery; import org.jmock.Expectations; public class AJMock2TestCase ... { Mockery context = new Mockery(); ... }

Show for: JUnit 3JUnit 4Other

JUnit 3 Integration

import org.jmock.integration.junit3.MockObjectTestCase; import org.jmock.Expectations; public class TurtleDrawingTest extends MockObjectTestCase { ... }

Show for: JUnit 3JUnit 4Other

JUnit 4 Integration

import org.jmock.Expectations; import org.jmock.Mockery; import org.jmock.integration.junit4.JMock; import org.jmock.integration.junit4.JUnit4Mockery; @RunWith(JMock.class) public class AJMock2TestCase { Mockery context = new JUnit4Mockery(); ... }

A represents the context of the object under test: the objects that it communicates with. A Mockery creates mock objects and checks expectations that are set upon those mock objects. By convention the Mockery is stored in an instance variable named .

Tests written with JUnit 3 can extend MockObjectTestCase, in which case they don't need to explictly create or refer to the context.

Tests written with JUnit 4 do not need to extend a specific base class but must specify that they use jMock with the attribute, create a JUnit4Mockery that reports expectation failures as JUnit 4 test failures, and store the Mockery in an instance variable.

Creating Mock Objects

Show for: JUnit 3JUnit 4Other

Raw

Turtle turtle = context.mock(Turtle.class); Turtle turtle2 = context.mock(Turtle.class, "turtle2");

Show for: JUnit 3JUnit 4Other

JUnit 3 Integration

Turtle turtle = mock(Turtle.class); Turtle turtle2 = mock(Turtle.class, "turtle2");

Show for: JUnit 3JUnit 4Other

JUnit 4 Integration

Turtle turtle = context.mock(Turtle.class); Turtle turtle2 = context.mock(Turtle.class, "turtle2");

The examples above assume that the mock object is stored in an instance variable. If a mock object is stored in a local variable, the variable must be declared as so that it can be referred to from within expectation blocks (see below).

Tests with Expectations

Show for: JUnit 3JUnit 4Other

Raw

... create mock objects ... public void testSomeAction() { ... set up ... context.checking(new Expectations() {{ ... expectations go here ... }}); ... call code being tested ... context.assertIsSatisfied(); ... other assertions ... }

Show for: JUnit 3JUnit 4Other

JUnit 3 Integration

... create mock objects ... public void testSomeAction() { ... set up ... checking(new Expectations() {{ ... expectations go here ... }}); ... call code being tested ... ... assertions ... }

Show for: JUnit 3JUnit 4Other

JUnit 4 Integration

... create mock objects ... public void testSomeAction() { ... set up ... context.checking(new Expectations() {{ ... expectations go here ... }}); ... call code being tested ... ... assertions ... }

The JUnit 3 and JUnit 4 integration layers automatically assert that all expectations have been satisfied.

An expectations block can contain any number of expectations. A test can contain multiple expectation blocks. Expectations in later blocks are appended to those in earlier blocks. Expectations can be interspersed with calls to the code under test.

Expectations

Expectations have the following structure:

().(); inSequence(); when(.is()); will(); then(.is());

Except for the invocation count and the mock object, all clauses are optional. You can give an expectation as many , , and clauses as you wish.

Some examples:

oneOf (turtle).turn(45); // The turtle will be told to turn 45 degrees once only allowing (turtle).flashLEDs(); // The turtle can be told to flash its LEDs any number of types or not at all ignoring (turtle2); // Turtle 2 can be told to do anything. This test ignores it. allowing (turtle).queryPen(); // The turtle can be asked about its pen any number of times and will always will(returnValue(PEN_DOWN)); // return PEN_DOWN atLeast(1).of (turtle).stop(); // The turtle will be told to stop at least once.

Invocation Count

oneOfThe invocation is expected once and once only.
exactly().ofThe invocation is expected exactly times. Note: is a convenient shorthand for .
atLeast().ofThe invocation is expected at least .
atMost().ofThe invocation is expected at most times.
between(, ).ofThe invocation is expected at least times and at most times.
allowingThe invocation is allowed any number of times but does not have to happen.
ignoringThe same as . Allowing or ignoring should be chosen to make the test code clearly express intent.
neverThe invocation is not expected at all. This is used to make tests more explicit and so easier to understand.

Methods And Expectations

Expected methods are specified by a literal call to the method within an expectation block.

Arguments passed to the method in an expectation will be compared for equality.

oneOf (calculator).add(1, 1); will(returnValue(2)); oneOf (calculator).add(2, 2); will(returnValue(5));

To define looser constraints, specify all arguments as matchers within clauses:

allowing (calculator).add(with(any(int.class)), with(any(int.class)));

Argument Matchers

The most commonly used matchers are defined in the Expectations class:

equal()The argument is equal to .
same()The argument is the same object as .
any(Class<T> type)The argument is any value. The type argument is required to force Java to type-check the argument at compile time.
a(Class<T> type)
an(Class<T> type)
The argument is an instance of or a subclass of .
aNull(Class<T> type)The argument is null. The type argument is required to force Java to type-check the argument at compile time.
aNonNull(Class<T> type)The argument is not null. The type argument is required to force Java to type-check the argument at compile time.
not()The argument does not match the Matcher .

More matchers are defined as static factory methods of the Hamcrest Matchers class, which can be statically imported at the top of the test code. For example,

anyOf(, , ..., )The argument matches one of the Matchers to .
allOf(, , ..., mn)The argument matches all of the Matchers to .

Actions

will(returnValue())Return to the caller.
will(returnIterator())Return a new iterator over collection on each invocation.
will(returnIterator(, , ..., ))Return a new iterator over elements to on each invocation.
will(throwException())Throw to the caller.
will(doAll(, , ..., ))Do all actions to on every invocation.

Sequences

Invocations that are expected in a sequence must occur in the order in which they appear in the test code. A test can create more than one sequence and an expectation can be part of more than once sequence at a time.

To define a new sequence:

Show for: JUnit 3JUnit 4Other

Raw

final Sequence = context.sequence("");

Show for: JUnit 3JUnit 4Other

JUnit 3

final Sequence = sequence("");

Show for: JUnit 3JUnit 4Other

JUnit 4

final Sequence = context.sequence("");

To expect a sequence of invocations, write the expectations in order and add the clause to each one. For example:

oneOf (turtle).forward(10); inSequence(drawing); oneOf (turtle).turn(45); inSequence(drawing); oneOf (turtle).forward(10); inSequence(drawing);

Expectations in a sequence can have any invocation count.

States

States are used to constrain invocations to occur only when a condition is true. Conditions are represented as states of state machines. A test can create multiple state machines and each state machine can have multiple states. An invocation can be constrained to occur during a state of one more more state machines.

To define a new state machine:

Show for: JUnit 3JUnit 4Other

Raw

final States = context.states("").startsAs("");

Show for: JUnit 3JUnit 4Other

JUnit 3

final States = states("").startsAs("");

Show for: JUnit 3JUnit 4Other

JUnit 4

final States = context.states("").startsAs("");

The intial state is optional. If not specified, the state machine starts in an unnamed initial state.

The following clauses constrain invocations to occur within specific states and define how an invocation will change the current state of a state machine.

when(.is(""));Constrains the last expectation to occur only when the state machine is in the named state.
then(.is(""));Changes the state of to the named state when the invocation occurs.

For example:

final States pen = context.states("pen").startsAs("up"); oneOf (turtle).penDown(); then(pen.is("down")); oneOf (turtle).forward(10); when(pen.is("down")); oneOf (turtle).turn(90); when(pen.is("down")); oneOf (turtle).forward(10); when(pen.is("down")); oneOf (turtle).penUp(); then(pen.is("up"));

Copyright © 2007 Nat Pryce.

Categories: 1

0 Replies to “Jmock Sequence Example Essay”

Leave a comment

L'indirizzo email non verrà pubblicato. I campi obbligatori sono contrassegnati *