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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

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
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

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Cypress.io — The Rising Future of Web Automation Testing
  • Why Testing is a Long-Term Investment for Software Engineers
  • Specification by Example Is Not a Test Framework
  • What Is API-First?

Trending

  • IoT and Cybersecurity: Addressing Data Privacy and Security Challenges
  • Prioritizing Cloud Security Risks: A Developer's Guide to Tackling Security Debt
  • Introduction to Retrieval Augmented Generation (RAG)
  • ITBench, Part 1: Next-Gen Benchmarking for IT Automation Evaluation
  1. DZone
  2. Coding
  3. Languages
  4. Dynamic Mock Testing

Dynamic Mock Testing

By 
Ant Kutschera user avatar
Ant Kutschera
·
Nov. 04, 10 · Interview
Likes (0)
Comment
Save
Tweet
Share
9.6K Views

Join the DZone community and get the full member experience.

Join For Free

Have you ever had to create a mock object in which most methods do nothing and are not called, but in others something useful needs to be done?

EasyMock has some newish functionality to let you stub individual methods. But before I had heard about that, I had built a little framework (one base class) for creating mock objects which stubs those methods you want to stub, as well as logging every call made to the classes being mocked.

It works like this: you choose a class which you need to mock, for example a service class called FooService, and you create a new class called FooServiceMock. You make it extend from AbstractMock<T>, where T is the class you are mocking.

As an example:

public class FooServiceMock extends AbstractMock<FooService> {

    public FooServiceMock() {
        super(FooService.class);
    }


It needs to have a constructor to call the super constructor passing the class being mocked too. Perhaps that could be optimised, I don't have too much time right now.

Next, you implement only those methods you expect to be called. For example:

public class FooServiceMock extends AbstractMock<FooService> {

    public FooServiceMock() {
        super(FooService.class);
    }

    /** 
     * this is a method which exists in FooService, 
     * but I want it to do something else.
     */
    public String sayHello(String name){
	    return "Hello " + name + 
              ", Foo here!  This is a stub method!";
    }	


To use the mock, you'll notice that it doesn't extend the class which it mocks, which might be problematic... Well, there are good reasons. To do the mocking, the abstract base class is actually going to create a dynamic proxy which wraps itself behind the interface of the class being mocked. To the caller, it looks like the FooService, but it's not actually anything related to it. Anytime a call to the FooService is made, the first thing which the proxy does is log that call, using XStream to create an XML representation of the parameters being passed into the method. Then, the proxy goes and looks in the instance of the mock class to see if it can find the method being called (well at least a method which takes the same parameters and has the same name and return type). If it finds such a method, it calls it. In our example, the sayHello(String) method would get called. It returns the result if there is one, to the caller.

In the case where it cannot find the method, it throws an exception, because it assumes that if it was not implemented, you didn't expect it to be called. You could of course change this to suit your needs, maybe even calling the actual FooService.

So, how to you use the FooServiceMock to create a FooService instance which you can use to mock your service? In the test, where you setup the class under test, you do this:

    FooServiceMock fooService = new FooServiceMock();
	
    //perhaps tell it about objects you would
    //like it to return...
	
    instanceOfClassUnderTest.setFooService(
                               fooService.getMock());	


The setFooService(FooService) method on the instance of the class you are testing is in my case present, but you might not have it and may need to use reflection to do it. It's a question of how testable you write your classes, and is a design choice.

The getMock() method on the AbstractMock class is the method which creates the dynamic proxy which wraps the instance of the mock.

You can now test the class. There is however still something useful you can do after testing, i.e. assert that the right calls were made in the correct order with the right parameters. You do this in the test class to:

    assertEquals(1, fooService.getCalls().size());
    assertEquals("[sayHello: <String>Ant</String>]", 
	                  fooService.getCalls().toString());


The above tests that the sayHello(String) method was called just once, and passed the name "Ant".

There are times when you might want to clear the call log, between parts of the test. For that, call the clearCalls() method on the mock object:

        fooService.clearCalls();


Have fun!

 

From http://blog.maxant.co.uk/pebble/2010/11/03/1288813500000.html

Testing Mock object Stub (distributed computing) Object (computer science) IT XStream Clear (Unix) Interface (computing)

Opinions expressed by DZone contributors are their own.

Related

  • Cypress.io — The Rising Future of Web Automation Testing
  • Why Testing is a Long-Term Investment for Software Engineers
  • Specification by Example Is Not a Test Framework
  • What Is API-First?

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!