DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
Building Scalable Real-Time Apps with AstraDB and Vaadin
Register Now

Trending

  • How To Integrate Microsoft Team With Cypress Cloud
  • Replacing Apache Hive, Elasticsearch, and PostgreSQL With Apache Doris
  • Integrating AWS With Salesforce Using Terraform
  • Scaling Site Reliability Engineering (SRE) Teams the Right Way

Trending

  • How To Integrate Microsoft Team With Cypress Cloud
  • Replacing Apache Hive, Elasticsearch, and PostgreSQL With Apache Doris
  • Integrating AWS With Salesforce Using Terraform
  • Scaling Site Reliability Engineering (SRE) Teams the Right Way
  1. DZone
  2. Coding
  3. Java
  4. Yet More Spock Magic: Mocks

Yet More Spock Magic: Mocks

Howard Lewis Ship user avatar by
Howard Lewis Ship
·
May. 04, 12 · Interview
Like (0)
Save
Tweet
Share
6.48K Views

Join the DZone community and get the full member experience.

Join For Free

Spock's built-in mock object capabilities are just a dream to use ... unlike other systems I've used, it doesn't get in your way, or force you to think backwards or inside out. Once again, some listings. These are for tests of Tapestry IoC's AspectDecorator service, which is used to create a wrapper interceptor around some other object. The test below shows how a supplied MethodAdvice callback object is invoked by the interceptor, if the advice is associated with the invoked method.

TestNG with EasyMock (Java)

public class AspectInterceptorBuilderImplTest extends IOCInternalTestCase
{
    private AspectDecorator decorator;

    @BeforeClass
    public void setup()
    {
        decorator = getService(AspectDecorator.class);
    }

    public interface Subject
    {
        void advised();

        void notAdvised();
    }

    @Test
    public void some_methods_not_intercepted() throws Exception
    {
        Subject delegate = newMock(Subject.class)

        MethodAdvice advice = new MethodAdvice()
        {
            public void advise(MethodInvocation invocation)
            {
                assertEquals(invocation.getMethod().getName(), "advised");

                invocation.proceed();
            }
        };

        delegate.advised();
        delegate.notAdvised();

        replay();

        AspectInterceptorBuilder<Subject> builder = decorator.createBuilder(Subject.class, delegate, "<Subject>");

        builder.adviseMethod(Subject.class.getMethod("advised"), advice);

        Subject interceptor = builder.build();

        interceptor.advised();
        interceptor.notAdvised();

        verify();
    }
}

Even this example is a bit streamlined, as some of the mock object capabilities, such as methods newMock(), replay() and verify() are being derived from the TestBase base class.

Spock

interface InterceptorSubject {

  void advised()

  void notAdvised()
}

class AspectInterceptorBuilderImplSpec extends AbstractSharedRegistrySpecification {

  @Shared
  private AspectDecorator decorator

  def setupSpec() {
    decorator = getService AspectDecorator
  }

  def "ensure that non-advised methods are not passed through the MethodAdvice object"() {
    InterceptorSubject delegate = Mock()
    MethodAdvice advice = Mock()

    def builder = decorator.createBuilder(InterceptorSubject, delegate, "<InterceptorSubject>")

    builder.adviseMethod(InterceptorSubject.getMethod("advised"), advice)

    InterceptorSubject interceptor = builder.build()

    when:

    interceptor.advised()

    then:

    1 * advice.advise(_) >> { MethodInvocation mi ->
      assert mi.method.name == "advised"
      mi.proceed()
    }
    1 * delegate.advised()
    0 * _

    when:

    interceptor.notAdvised()

    then:

    1 * delegate.notAdvised()
    0 * _
  }

}

Spock's wonderful when: / then: blocks organize the behavior into a stimulus followed by a response; using EasyMock, you have to train the mock objects for the response before introducing the stimulus (the method invocation). Further, with EasyMock there's one API for methods that return a fixed response, a second API for methods that throw an exception, and a third API for methods where the result must be calculated; in Spock the value after the >> operator is either a literal value, or a closure that can do what it likes, such as the one attached to MethodAdvice.advice() that checks for the expected method name, and then proceed()s to the delegate mock object's method.

I think that a reasonable developer, even without a thorough understanding of Spock, would get the gist of what this test does (perhaps with a little side note about the interaction system inside the then: block). On the other hand, I've seen when training people with TestNG and EasyMock that it very rarely sinks in immediately, if at all.

 

 

 

 

Spock (testing framework)

Published at DZone with permission of Howard Lewis Ship, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Trending

  • How To Integrate Microsoft Team With Cypress Cloud
  • Replacing Apache Hive, Elasticsearch, and PostgreSQL With Apache Doris
  • Integrating AWS With Salesforce Using Terraform
  • Scaling Site Reliability Engineering (SRE) Teams the Right Way

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com

Let's be friends: