Stubs and Mocking

Steven J Zeil

Last modified: Dec 21, 2019
Contents:

Abstract

The *Unit frameworks that we have looked at provide powerful support for writing test drivers. But we know that scaffolding comes in two forms: drivers and stubs.

In this lesson, we look at a modern approach to stubs, mock objects. Suppose that we are testing class A and that A calls functions from a class B. A mock object for B is interface-compatible with B, but combines a simple (possibly automatically-generated) implementation together with test instrumentation to help us determine if A is calling upon B properly during testing.

1 Stubs

The Lowly Stub


Where ADTs and Stubs Meet

In some ways, ADTs and OOP make it easier to do stubs.

A mock object is an object whose interface emulates a “real” class for testing purposes.

Mock objects may …


Example: Mailing List

In our MailingList tests, we relied on a Contact class.

Here is the real interface for Contact:

contactnmad.h
#ifndef CONTACT_H
#define CONTACT_H

#include <iostream>
#include <string>

#include "name.h"
#include "address.h"

class Contact {
  Name theName;
  Address theAddress;

public:
  Contact (Name nm, Address addr)
    : theName(nm), theAddress(addr)
  {}


  Name getName() const   {return theName;}
  void setName (Name nm) {theName= nm;}

  Address getAddress() const     {return theAddress;}
  void setAddress (Address addr) {theAddress = addr;}

  bool operator== (const Contact& right) const
  {
    return theName == right.theName
      && theAddress == right.theAddress;
  }

  bool operator< (const Contact& right) const
  {
    return (theName < right.theName)
      || (theName == right.theName
	  && theAddress < right.theAddress);
  }
};

inline
std::ostream& operator<< (std::ostream& out, const Contact& c)
{
  out << c.getName() << " @ " << c.getAddress();
  return out;
}


#endif

#ifndef NAME_H
#define NAME_H

#include <iostream>
#include <string>

struct Name {
  std::string last;
  std::string first;
  std::string middle;


  Name (std::string lastName,
	   std::string firstName,
	   std::string middleName)
    : last(lastName), first(firstName),
      middle(middleName)
    {}

  bool operator== (const Name& right) const;
  bool operator< (const Name& right) const;

};

std::ostream& operator<< (std::ostream& out, const Name& addr);


#endif


#ifndef ADDRESS_H
#define ADDRESS_H

#include <iostream>
#include <string>

struct Address {
  std::string street1;
  std::string street2;
  std::string city;
  std::string state;
  std::string zipcode;

  Address (std::string str1,
	   std::string str2,
	   std::string cty,
	   std::string stte,
	   std::string zip)
    : street1(str1), street2(str2),
      city(cty), state(stte), zipcode(zip)
    {}

  bool operator== (const Address& right) const;
  bool operator< (const Address& right) const;

};

std::ostream& operator<< (std::ostream& out, const Address& addr);


#endif

What Do We Need for the MailingList Test?

But in our tests, the only things we needed to do with contacts was


A Mock Contact

So we made do with a simpler interface that

contact.h
#ifndef CONTACT_H
#define CONTACT_H

#include <iostream>
#include <string>

typedef std::string Name;
typedef std::string Address;

class Contact {
  Name theName;
  Address theAddress;

public:
  Contact() {}

  Contact (Name nm, Address addr)
    : theName(nm), theAddress(addr)
  {}


  Name getName() const   {return theName;}
  void setName (Name nm) {theName= nm;}

  Address getAddress() const     {return theAddress;}
  void setAddress (Address addr) {theAddress = addr;}

  bool operator== (const Contact& right) const
  {
    return theName == right.theName
      && theAddress == right.theAddress;
  }

  bool operator< (const Contact& right) const
  {
    return (theName < right.theName)
      || (theName == right.theName
          && theAddress < right.theAddress);
  }
};

inline
std::ostream& operator<< (std::ostream& out, const Contact& c)
{
  out << c.getName() << " @ " << c.getAddress();
  return out;
}


#endif

Replacing the Name and Address classes by simple strings.

2 Mock Objects

Object-oriented languages make it easier to create some mock objects

Example: for an application that drew graphics using the Java java.awt.Graphics API, I created the following as a mock class:

GraphicsStub.java
package Pictures;

import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.image.ImageObserver;
import java.text.AttributedCharacterIterator;

/**
 * Special version of Graphics for testing that simply writes all graphics requests to
 * a string.
 * 
 * @author zeil
 *
 */
public class GraphicsStub extends Graphics {

    private StringBuffer log;

    public GraphicsStub() {
        log = new StringBuffer();
    }

    public void clearRect(int arg0, int arg1, int arg2, int arg3) {
        entering("clearRect",
                "" + arg0 + ":" + arg1 + ":" + arg2 + ":" + arg3);
    }

    public void clipRect(int arg0, int arg1, int arg2, int arg3) {
        entering("clipRect",
                "" + arg0 + ":" + arg1 + ":" + arg2 + ":" + arg3);
    }

    public void copyArea(int arg0, int arg1, int arg2, int arg3, int arg4,
            int arg5) {
        entering("copyArea",
                "" + arg0 + ":" + arg1 + ":" + arg2 + ":" + arg3 + ":" + arg4 + ":" + arg5);
    }

    public Graphics create() {
        entering("create", "");
        return new GraphicsStub();
    }

    public void dispose() {
        entering("dispose", "");
    }

    public void drawArc(int arg0, int arg1, int arg2, int arg3, int arg4,
            int arg5) {
        entering("drawArc",
                "" + arg0 + ":" + arg1 + ":" + arg2 + ":" + arg3 + ":" + arg4 + ":" + arg5);
    }

    public boolean drawImage(Image arg0, int arg1, int arg2, ImageObserver arg3) {
        entering("drawImage",
                "" + arg0 + ":" + arg1 + ":" + arg2 + ":" + arg3);
        return true;
    }

    public boolean drawImage(Image arg0, int arg1, int arg2, Color arg3,
            ImageObserver arg4) {
        entering("drawImage",
                "" + arg0 + ":" + arg1 + ":" + arg2 + ":" + arg3);
        return true;
    }

    public boolean drawImage(Image arg0, int arg1, int arg2, int arg3,
            int arg4, ImageObserver arg5) {
        entering("drawImage",
                "" + arg0 + ":" + arg1 + ":" + arg2 + ":" + arg3 + ":" + arg4);
        return true;
    }

    public boolean drawImage(Image arg0, int arg1, int arg2, int arg3,
            int arg4, Color arg5, ImageObserver arg6) {
        entering("drawImage",
                "" + arg0 + ":" + arg1 + ":" + arg2 + ":" + arg3 + ":" + arg4 + ":" + arg5);
        return true;
    }

    public boolean drawImage(Image arg0, int arg1, int arg2, int arg3,
            int arg4, int arg5, int arg6, int arg7, int arg8, ImageObserver arg9) {
        entering("drawImage",
                "" + arg0 + ":" + arg1 + ":" + arg2 + ":" + arg3 + ":" + arg4 + ":" + arg5
                + arg6 + ":" + arg7 + ":" + arg8);
        return true;
    }

    public boolean drawImage(Image arg0, int arg1, int arg2, int arg3,
            int arg4, int arg5, int arg6, int arg7, int arg8, Color arg9,
            ImageObserver arg10) {
        entering("drawImage",
                "" + arg0 + ":" + arg1 + ":" + arg2 + ":" + arg3 + ":" + arg4 + ":" + arg5
                + arg6 + ":" + arg7 + ":" + arg8 + ":" + arg9);
        return true;
    }

    public void drawLine(int arg0, int arg1, int arg2, int arg3) {
        entering("drawLine",
                "" + arg0 + ":" + arg1 + ":" + arg2 + ":" + arg3);
    }

    public void drawOval(int arg0, int arg1, int arg2, int arg3) {
        entering("drawOval",
                "" + arg0 + ":" + arg1 + ":" + arg2 + ":" + arg3);
    }

    public void drawPolygon(int[] arg0, int[] arg1, int arg2) {
        entering("drawPolygon",
                "" + arg0 + ":" + arg1 + ":" + arg2);
    }

    public void drawPolyline(int[] arg0, int[] arg1, int arg2) {
        entering("drawPolyline",
                "" + arg0 + ":" + arg1 + ":" + arg2);
    }

    public void drawRoundRect(int arg0, int arg1, int arg2, int arg3, int arg4,
            int arg5) {
        entering("drawRoundRect",
                "" + arg0 + ":" + arg1 + ":" + arg2 + ":" + arg3 + ":" + arg4 + ":" + arg5);
    }

    public void drawString(String arg0, int arg1, int arg2) {
        entering("drawString",
                "" + arg0 + ":" + arg1 + ":" + arg2);
    }

    public void drawString(AttributedCharacterIterator arg0, int arg1, int arg2) {
        entering("drawString",
                "" + arg0 + ":" + arg1 + ":" + arg2);
    }

    public void fillArc(int arg0, int arg1, int arg2, int arg3, int arg4,
            int arg5) {
        entering("fillArc",
                "" + arg0 + ":" + arg1 + ":" + arg2 + ":" + arg3 + ":" + arg4 + ":" + arg5);
    }

    public void fillOval(int arg0, int arg1, int arg2, int arg3) {
        entering("fillOval",
                "" + arg0 + ":" + arg1 + ":" + arg2 + ":" + arg3);
    }

    public void fillPolygon(int[] arg0, int[] arg1, int arg2) {
        entering("fillPolygon",
                "" + arg0 + ":" + arg1 + ":" + arg2);
    }

    public void fillRect(int arg0, int arg1, int arg2, int arg3) {
        entering("fillRect",
                "" + arg0 + ":" + arg1 + ":" + arg2 + ":" + arg3);
    }

    public void fillRoundRect(int arg0, int arg1, int arg2, int arg3, int arg4,
            int arg5) {
        entering("fillRoundRect",
                "" + arg0 + ":" + arg1 + ":" + arg2 + ":" + arg3 + ":" + arg4 + ":" + arg5);
    }

    private Shape clip = null;
    public Shape getClip() {
        return clip;
    }

    public Rectangle getClipBounds() {
        return null;
    }

    private Color color;
    public Color getColor() {
        return color;
    }

    public Font getFont() {
        return null;
    }

    public FontMetrics getFontMetrics(Font arg0) {
        return null;
    }

    public void setClip(Shape arg0) {
        entering("setClip",
                "" + arg0);
        clip = arg0;
    }

    public void setClip(int arg0, int arg1, int arg2, int arg3) {
        entering("setClip",
                "" + arg0 + ":" + arg1 + ":" + arg2 + ":" + arg3);
    }

    public void setColor(Color arg0) {
        entering("setColor",
                "" + arg0);
        color = arg0;
    }

    public void setFont(Font arg0) {
        entering("setFont",
                "" + arg0);
    }

    public void setPaintMode() {
        entering("setPaintMode", "");
    }

    public void setXORMode(Color arg0) {
        entering("setXORMode",
                "" + arg0);
    }

    public void translate(int arg0, int arg1) {
        entering("translate",
                "" + arg0 + ":" + arg1);
    }

    public String toString()
    {
        return log.toString();
    }

    public void clear()
    {
        log = new StringBuffer();
    }

    private void entering(String functionName, String args)
    {
        log.append(functionName);
        log.append(": ");
        log.append(args);
        log.append("\n");
    }

}

It basically writes each successive graphics call into a string, that can later be examined by unit test cases.


OO Mock Example

Here is a test using that mock:

linesegTest.java
package PictureTests;
import java.awt.Color;
import java.awt.Point;
import java.lang.reflect.Method;
import java.util.Scanner;

import junit.framework.*;
import junit.textui.TestRunner;
import Pictures.GraphicsStub;
import Pictures.LineSegment;
import Pictures.Shape;


/**
 * Test of the LineSegment class
 */
public class LineSegmentTest extends TestCase {
    ⋮
    public void testPlot()
    {
        Point p1 = new Point(22, 341);
        Point p2 = new Point(104, 106);
        LineSegment ls = new LineSegment(p1, p2, Color.blue, Color.red);
        
        GraphicsStub g = new GraphicsStub();
        GraphicsStub gblue = new GraphicsStub();
        gblue.setColor(Color.blue);
        GraphicsStub gline1 = new GraphicsStub();
        gline1.drawLine(22, 341, 104, 106);
        GraphicsStub gline2 = new GraphicsStub();
        gline2.drawLine(104, 106, 22, 341);

        ls.plot(g);
        assertTrue (g.toString().contains(gblue.toString()));
        assertTrue (g.toString().contains(gline1.toString()) 
                    || g.toString().contains(gline2.toString()));
    }
    ⋮

Mock Frameworks

Increasingly, unit test frameworks are including special support for mock object creation.

2.1 Google Mock (C++)


**Mocking Up an Example **

Suppose that we are writing an application that uses this class:

class Turtle {
  ⋮
  virtual ~Turtle() {}
  virtual void PenUp() = 0;
  virtual void PenDown() = 0;
  virtual void Forward(int distance) = 0;
  virtual void Turn(int degrees) = 0;
  virtual void GoTo(int x, int y) = 0;
  virtual int GetX() const = 0;
  virtual int GetY() const = 0;
};

To set up the test of the application code that uses this, we derive a mock class that has the same interface…


A Mock Class

#include "gmock/gmock.h"
class MockTurtle : public Turtle {
 public:
  ...
  MOCK_METHOD0(PenUp, void());
  MOCK_METHOD0(PenDown, void());
  MOCK_METHOD1(Forward, void(int distance));
  MOCK_METHOD1(Turn, void(int degrees));
  MOCK_METHOD2(GoTo, void(int x, int y));
  MOCK_CONST_METHOD0(GetX, int());
  MOCK_CONST_METHOD0(GetY, int());
};

Using the Mock

Then in unit tests for the application class, we

  1. use instances of the mock class
  2. Write assertions that describe how we expect the stub to be exercised.
#include "mock-turtle.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
using ::testing::AtLeast;

TEST(DrawACircle, CanDrawSomething) {
  MockTurtle turtle;
  EXPECT_CALL(turtle, PenDown())
      .Times(AtLeast(1));
  Painter painter(&turtle);
  EXPECT_TRUE(painter.DrawCircle(0, 0, 10));
}

So, if we call painter.drawCircle(...), we


Stubs can Generate Output

EXPECT_CALL(g, foo(_))
    .TIMES(3)
    .WillRepeatedly(Return(150));
EXPECT_CALL(g, foo(1))
    .WillOnce(Return(100));
EXPECT_CALL(g, foo(2))
    .WillOnce(Return(200));

This assertion says

2.2 JMockit (Java)

There are a number of popular mocking frameworks for Java: JMock, EasyMock, Mockito

JMockit is one of newer ones.

2.2.1 The Record-Replay-Verify Model

A test with JMockit mock objects typically follows a structure of

Record
We establish our expectations of what calls will be made on our mock objects by separately executing those calls in a recording mode.

In this phase we also record any return/output values we want our mocks to return from those calls.

Replay
We actually perform the test, calling upon some functions of the ADT under test that, in the run, we expect will make those calls on the mocks. The actual calls made are compared against the “recording” we made earlier.

We fail the test if we do not see the expected (recorded) calls.

Verify
More detailed checks are made to see if the test matched criteria other than simply having called the expected functions in the expected order.

We may check the parameters supplied to those calls and/or check to see that other mock functions were not called.

3 Case Studies

3.1 Example 1 (Spreadsheet CLI)

In our spreadsheet example, we had these stories in the first increment:

I decided to merge these as, together, they represented the minimum testable behavior on the CLI.

However, during this first project increment, the spreadsheet itself has not been implemented.

I had, for an earlier story, taken a first pass at designing the spreadsheet API:

package edu.odu.cs.espreadsheet;

    ⋮

public class Spreadsheet implements Iterable<CellName> {

	public Spreadsheet()
	{
		// TODO
	}


    ⋮

	/**
	 * Loads a spreadsheet from a file or other input source. Input format is
	 * one assignment per line.
	 *
	 * @param input an input source
	 * @throws IOException if assignments cannot be parsed form the input.
	 */
	public void load (Reader input) throws IOException
	{
		// TODO Auto-generated method stub
	}

	⋮

	/**
	 * Write out the value report for the spreadsheet, giving the current value of
	 * each non-empty cell.
	 *
	 * @param output output device
	 */
	public void report (Writer output)
	{
		// TODO Auto-generated method stub
	}

}

The CLI

I expected the CLI to look something like:

package edu.odu.cs.espreadsheet.cli;

    ⋮

import edu.odu.cs.espreadsheet.Spreadsheet;

public class Run {
    ⋮

	public Run(String filename)
	{
	  // TODO
	}

	/**
	 * Load the indicated spreadsheet and generate its value report.
	 * @throws IOException if the spreadsheet cannot be loaded
	 */
	public void doIt() throws IOException
	{
		⋮
	}


	public static void main (String[] args) throws FileNotFoundException, IOException {
		if (args.length != 1) {
			System.err.println("Usage: must supply a path to a spreadsheet file as a command line parameter.");
			System.exit(-1);
		}
		new Run(args[0]).doIt();
	}

}

because this is a pretty standard pattern for me.


Testing With a Spreadsheet

Now, if I had been working bottom-up, then by the time I looked at the CLI, I would have a working spreadsheet and could write some “real” tests of the CLI:

ITestCLI.java
package edu.odu.cs.espreadsheet.cli;

import static org.junit.Assert.assertTrue;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;

import org.junit.BeforeClass;
import org.junit.Test;

public final class ITestCLI {

	static Path testDataDir = Paths.get("target/itest-data");
	
	@BeforeClass
	public static void setupDir()
	{
		File dir = testDataDir.toFile();
		dir.mkdir();
	}
	
	@Test
	public void testRunNonExistentFile() throws FileNotFoundException, IOException {
		Run running = new Run("target/testdata/nonExistent.ss");

		boolean thrown = false;
		try {
			running.doIt();
		} catch (FileNotFoundException ex) {
			thrown = true;
		}
		assertTrue (thrown);
	}

	
	@Test
	public void testBadFile() throws FileNotFoundException, IOException {
		
		Path badDataPath = testDataDir.resolve("badData.ss");
		Files.write(badDataPath, 
				Arrays.asList("a12", "ab2=1"), 
				Charset.forName("US-ASCII"));

		Run running = new Run(badDataPath.toString());
		boolean thrown = false;
		try {
			running.doIt();
		} catch (IOException ex) {
			thrown = true;
		}
		assertTrue (thrown);
	}

	@Test
	public void testSimpleAssignments() throws FileNotFoundException, IOException {
		
		Path simpleDataPath = testDataDir.resolve("simpleData.ss");
		Files.write(simpleDataPath, 
				Arrays.asList("a12=12", "ab2=1"), 
				Charset.forName("US-ASCII"));
		
		// Capture System.out
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
	    PrintStream stringStream = new PrintStream(baos);
	    PrintStream savedOut = System.out;
	    System.setOut (stringStream);
	    
		try {
			Run running = new Run(simpleDataPath.toString());
			running.doIt();
		} finally {
			//Restore System.out
			System.out.flush();
			System.setOut(savedOut);
		}
		String reportOutput = baos.toString();
		assertTrue (reportOutput.startsWith("a12=12"));
		assertTrue (reportOutput.contains("ab2=1"));	
	}

	@Test
	public void testEvaluationPerformed() throws FileNotFoundException, IOException {
		
		Path simpleDataPath = testDataDir.resolve("evalData.ss");
		
		Files.write(simpleDataPath, 
				Arrays.asList("a12=10*ab2", "ab2=2"), 
				Charset.forName("US-ASCII"));
		
		// Capture System.out
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
	    PrintStream stringStream = new PrintStream(baos);
	    PrintStream savedOut = System.out;
	    System.setOut (stringStream);
	    
		try {
			Run running = new Run(simpleDataPath.toString());
			running.doIt();
		} finally {
			//Restore System.out
			System.out.flush();
			System.setOut(savedOut);
		}
		String reportOutput = baos.toString();
		assertTrue (reportOutput.startsWith("a12=20"));
		assertTrue (reportOutput.contains("ab2=2"));	
	}
	
	
}

This has tests for the cases:


Problems with that Test

This is actually an integration or system test, not a unit test.


Unit Testing Without a Spreadsheet

For a unit test of the CLI, I can mock the spreadsheet:

TestCLI.java
package edu.odu.cs.espreadsheet.cli;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;

import mockit.Expectations;
import mockit.Mocked;

import org.junit.Test;

import edu.odu.cs.espreadsheet.Spreadsheet;

public final class TestCLI {

	
    @Mocked Spreadsheet ss; ➀
	
	@Test
	public void testRun() throws FileNotFoundException, IOException {
		// Record phase: expectations on mocks are recorded; empty if there is nothing to record.
		new Expectations() {{  ➁
		    ss.load(withAny((Reader)null));   ➂
		    ss.report(withAny((Writer)null)); ➃
		}};


		// Replay phase: invocations on mocks are "replayed"; here the code under test is exercised.
		Run running = new Run("ivy.xml"); ➄
		running.doIt();
		
		// Verify phase: expectations on mocks are verified; empty if there is nothing to verify.
		➅
	}

}

Are We OK With This?

You might argue that this test is

3.2 Example 2: Adding Numeric Literals to the Spreadsheet

Shortly after the prior example, I had the story:

As an API user I would like to add a numeric literal to a cell in a spreadsheet.

The task list I came up with for this was:

  1. Check Spreadsheet API
  2. Design Cell API
  3. Design Expression API
  4. Add Unit test to Spreadsheet
  5. Add Integration test to Spreadsheet
  6. Add Unit test to Expression
  7. Add Unit test to Cell
  8. Implement Expression parse for numeric literals
  9. Implement Cell storage of expressions
  10. Implement Spreadsheet expression load
  11. Check in changes.

That may look like a lot, but it boils down to a common pattern:

  1. Make changes to the API to support the new functionality
  2. Write Unit tests for the new functionality
  3. If any of those tests used stubs or mocks, write integration or system tests for the behavior.
  4. Implement the new functionality
  5. Wrap things up

We expect that, at the end of step 4, we will pass all the new units tests devised in step 2.

3.2.1 Adding to the APIs

I made a conscious decision not to expose the internal Expression class as part of the API:

old

package edu.odu.cs.espreadsheet;
   ⋮
public class Spreadsheet implements Iterable<CellName> {
   ⋮

	/**
	 * Get the formula stored in the indicated cell.
	 *
	 * @param cell a cell in the spreadsheet
	 * @return the formula in that cell, or null if no formula has been placed there
	 */
	public Expression getFormula (CellName cell)
	{
	    ⋮
	}


	/**
	 * Assigns a formula to the indicated cell.
	 *
	 * @param cell a cell in the spreadsheet
	 * @param newFormula an expression for future evaluation (may be null)
	 * @throws ExpressionParseError if assignments cannot be parsed from the input.
	 */
	public void assignFormula (CellName cell, Expression newFormula) throws ExpressionParseError
	{
	    ⋮
	}

    ⋮
}

new

package edu.odu.cs.espreadsheet;
   ⋮
public class Spreadsheet implements Iterable<CellName> {
   ⋮

	/**
	 * Get the formula stored in the indicated cell.
	 *
	 * @param cell a cell in the spreadsheet
	 * @return the formula in that cell, or null if no formula has been placed there
	 */
	public String getFormula (CellName cell)
	{
	    ⋮
	}


	/**
	 * Assigns a formula to the indicated cell.
	 *
	 * @param cell a cell in the spreadsheet
	 * @param newFormula an expression for future evaluation (may be null)
	 * @throws ExpressionParseError if assignments cannot be parsed from the input.
	 */
	public void assignFormula (CellName cell, String newFormula) throws ExpressionParseError
	{
	    ⋮
	}

    ⋮
}

A welcome side effect of this change is to make independent testing of these classes even easier.


Cells contain Expressions

Cell.java
package edu.odu.cs.espreadsheet;

import edu.odu.cs.espreadsheet.expressions.Expression;
import edu.odu.cs.espreadsheet.values.Value;


/**
 * A single cell withing a spreadsheet.
 * 
 * @author zeil
 *
 */
public
class Cell
{

        private Spreadsheet ssheet;
        private CellName name;
        private Expression formula;
        private Value value;


        /**
         * Create a new cell
         * @param sheet the spreadsheet containing this cell
         * @param name  the name of this cell
         */
        public Cell (Spreadsheet ssheet, CellName name)
        {
                this.ssheet = ssheet;
                this.name = name;
                this.formula = null;
                this.value = null;
        }


        public CellName getName() 
        {
                return name;
        }

        /**
         * Get the formula associated with this cell.
         * 
         * @return an expression or null if the cell is empty
         */
        public Expression getFormula() 
        {
                return formula;
        }

        public void putFormula(Expression e)
        {
                formula = e;
                value = null;
        }

        public Value getValue() 
        {
                if (value == null && formula != null)
                        value = formula.evaluate(ssheet);
                return value;
        }


        public String toString()
        {
                return name.toString() + "::" + formula + "::" + value;
        }


        public int hashCode()
        {
                return name.hashCode();
        }

        public boolean equals(Object obj)
        {
                if (obj instanceof Cell) {
                        Cell other = (Cell)obj;
                        return name.equals(other.name);
                } else
                        return false;
        }




}

Expressions can be Evaluated

Expression.java
package edu.odu.cs.espreadsheet.expressions;

import java.io.StringReader;

import edu.odu.cs.espreadsheet.ExpressionParseError;
import edu.odu.cs.espreadsheet.Spreadsheet;
import edu.odu.cs.espreadsheet.values.Value;


/**
 * Expressions can be thought of as trees.  Each non-leaf node of the tree
 * contains an operator, and the children of that node are the subexpressions
 * (operands) that the operator operates upon.  Constants, cell references,
 * and the like form the leaves of the tree.
 * 
 * For example, the expression (a2 + 2) * c26 is equivalent to the tree:
 * 
 *              *
 *             / \
 *            +   c26
 *           / \
 *         a2   2
 * 
 * @author zeil
 *
 */
public abstract class Expression implements Cloneable
{

        /**
         *  How many operands does this expression node have?
         *  
         * @return # of operands required by this operator
         */
        public abstract int arity();

        /**
         *  Get the k_th operand
         * @param k operand number
         * @return k_th operand if 0 < k < arity()
         * @throws IndexOutOfBoundsException if k is outside of those bounds
         */
        public abstract Expression operand(int k) throws IndexOutOfBoundsException;


        /**
         *  Evaluate this expression, using the provided spreadsheet to resolve 
         *  any cell referneces.
         *  
         * @param usingSheet spreadsheet form which to obtain values of 
         * cells referenced by this expression
         * 
         * @return value of the expression or null if the cell is empty
         */
        public abstract Value evaluate(Spreadsheet usingSheet);





        /**
         * Copy this expression (deep copy), altering any cell references
         * by the indicated offsets except where the row or column is "fixed"
         * by a preceding $. E.g., if e is  2*D4+C$2/$A$1, then
         * e.copy(1,2) is 2*E6+D$2/$A$1, e.copy(-1,4) is 2*C8+B$2/$A$1
         * 
         * @param colOffset number of columns to offset this copy
         * @param rowOffset number of rows to offset this copy
         * @return a copy of this expression, suitable for placing into 
         *           a cell (ColOffSet,rowOffset) away from its current position.
         *             
         */
        public abstract Expression clone (int colOffset, int rowOffset);

        /**
         * Copy this expression.
         */
        @Override
        public Expression clone ()
        {
                return clone(0,0);
        }


        /**
         * Attempt to convert the given string into an expression.
         * @param in
         * @return
         */
        public static Expression parse (String in) throws ExpressionParseError
        {
                try {
                        parser p = new parser(new ExpressionScanner(new StringReader(in)));
                    Expression expr = (Expression)p.parse().value;
                    return expr;
                } catch (Exception ex) {
                        throw new ExpressionParseError("Cannnot parse " + in);
                }
        }


        @Override
        public String toString ()
        {
	    ⋮
        }


        @Override
        public abstract boolean equals (Object obj);
        
        @Override
        public abstract int hashCode ();
        
        

        // The following control how the expression gets printed by 
        // the default implementation of toString

        /**
         * If true, print in inline form.
         * If false, print as functionName(comma-separated-list).
         * 
         * @return indication of whether to print in inline form.
         * 
         */
        public abstract boolean isInline();

        /**
         * Parentheses are placed around an expression whenever its precedence
         * is lower than the precedence of an operator (expression) applied to it.
         * E.g., * has higher precedence than +, so we print 3*(a1+1) but not
         * (3*a1)+1
         * 
         * @return precedence of this operator
         */
        public abstract int precedence();


        /**
         * Returns the name of the operator for printing purposes.
         * For constants/literals, this is the string version of the constant value.
         * 
         * @return the name of the operator for printing purposes.
         */
        public abstract String getOperator();



}

A lot of this design was lifted from an earlier project of mine.


Numeric Literals

This story requires just enough expression handling to deal with numeric literals. So we’ll need an API for numeric literals. We’ve already covered that, however.

3.2.2 Writing the Unit tests

NumericLiteral

NumericLiteral needs a good set of unit test cases. We’ve looked at those tests earlier.

The NumericLiteral test is a good example of unit testing, but did not use stubs or mocks.


Cells

Although I had a task to create a unit test for Cell, currently it really only has encapsulated data member get/set functions, so I gave that a pass.


Spreadsheet

An existing unit test for spreadsheets was augmented to cover this story of inserting numeric literals.

MockTestSpreadSheet.java
/**
 * 
 */
package edu.odu.cs.espreadsheet;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import mockit.Expectations;
import mockit.Mocked;

import org.junit.Test;

import edu.odu.cs.espreadsheet.expressions.Expression;
import edu.odu.cs.espreadsheet.expressions.NumericLiteral;

/**
 * @author zeil
 *
 */
public class MockTestSpreadSheet {
        
        @Mocked Expression expr;

        @Test
        public final void testConstructor() {
                Spreadsheet s = new Spreadsheet();
                assertEquals (0, s.getDimension());
                assertNull (s.getFormula(new CellName("a1")));
                assertFalse (s.iterator().hasNext());
        }
        
        
        @Test
        public final void testNumericLiteralInsertion() throws ExpressionParseError {
                
                final Spreadsheet s = new Spreadsheet();
                final String input = "1.234";

                new Expectations() {{
                        Expression.parse(input); result = new NumericLiteral(input);
                        expr.toString(); result = "1.234";
                }};
                
                CellName cn = new CellName("a1");
                assertNull (s.getFormula(cn));
                assertNull (s.getValue(cn));
                s.assignFormula(cn, input);
                assertEquals (input, s.getFormula(cn));
        }
        
        @Test(expected = ExpressionParseError.class)
        public final void testParsingError() throws ExpressionParseError {
                
                final Spreadsheet s = new Spreadsheet();
                final String input = "1.23.4";
                new Expectations() {{
                        Expression.parse(input); result = new ExpressionParseError();
                }};

                CellName cn = new CellName("b2");
                assertNull (s.getFormula(cn));
                assertNull (s.getValue(cn));
                s.assignFormula(cn, input);
                assertTrue(false);
        }

        
        
}

New Expression test case 1

Let’s break this testcase down:

public final void testNumericLiteralInsertion() throws ExpressionParseError {

		final Spreadsheet s = new Spreadsheet();
		final String input = "1.234";

		new Expectations() {{   ➀
				Expression.parse(input); result = new NumericLiteral(input);
				expr.toString(); result = "1.234";
		}};

		CellName cn = new CellName("a1");
		assertNull (s.getFormula(cn));
		assertNull (s.getValue(cn));
		s.assignFormula(cn, input);       ➁
		assertEquals (input, s.getFormula(cn));   ➂
}

New Expression test case 2

The other new test case starts with a similar structure:

@Test(expected = ExpressionParseError.class)
public final void testParsingError() throws ExpressionParseError {

		final Spreadsheet s = new Spreadsheet();
		final String input = "1.23.4";
		new Expectations() {{
				Expression.parse(input); result = new ExpressionParseError();
		}};

		CellName cn = new CellName("b2");
		assertNull (s.getFormula(cn));
		assertNull (s.getValue(cn));
		s.assignFormula(cn, input);
		assertTrue(false);
}

But in this case we are supplying an invalid input:

3.2.3 Integration Tests

Because one of our new unit tests used mocks, we should add an integration to system test now that we will fail now but will pass some time in the future when the missing modules have been implemented:

ITestSpreadSheet.java
package edu.odu.cs.espreadsheet;


import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;

import java.io.IOException;
import java.io.StringReader;

import org.junit.Test;

import edu.odu.cs.espreadsheet.values.NumericValue;
import edu.odu.cs.espreadsheet.values.Value;

/**
 * @author zeil
 *
 */
public class ITestSpreadSheet {
        
        

        @Test
        public final void testConstructor() {
                Spreadsheet s = new Spreadsheet();
                assertEquals (0, s.getDimension());
                assertNull (s.getFormula(new CellName("a1")));
                assertFalse (s.iterator().hasNext());
        }
        
        
    @Test
        public final void testNumericLiteralInsertion() throws ExpressionParseError {
                
                final Spreadsheet s = new Spreadsheet();

                CellName cn = new CellName("a1");
                assertNull (s.getFormula(cn));
                assertNull (s.getValue(cn));
                s.assignFormula(cn, "1.234");
                assertEquals ("1.234", s.getFormula(cn));
                Value v = s.getValue(cn);
                assertNotNull(v);
                assertTrue (v instanceof NumericValue);
                NumericValue nv = (NumericValue)v;
                assertEquals (1.234, nv.getDouble(), 0.0001);
        }
        
        @Test
        public final void testParsingError() {
                
                final Spreadsheet s = new Spreadsheet();

                CellName cn = new CellName("b2");
                assertNull (s.getFormula(cn));
                assertNull (s.getValue(cn));
                boolean thrown = false;
                try {
                        s.assignFormula(cn, "1.23.4");
                } catch (ExpressionParseError e) {
                        thrown = true;
                }
                assertTrue (thrown);
                
                assertNull (s.getFormula(cn));
                Value v = s.getValue(cn);
                assertNull(v);
        }

}

4 Are Mock Frameworks Useful?