Please refer to the previous tutorial Class instantiation with constructor. In this tutorial we will show how to use a factory method to instantiate an object.
You can find the code relating to this tutorial on Github in the
Method under test
SimpleSteps is an extremely simple class. All it does is record the number of steps taken. It can be initialized with a number of steps.
The method under test in this tutorial is
addSteps(). This does nothing other than add 1 to the number of steps taken.
Notice that we have implemented the
equals() method for this class. This is important in any cases where you want to "assert equals" in the test. Please read this page for more information on implementing equals().
First, right-click the
addSteps()method and choose Test with DevMate. Save the file. It will automatically open up the DevMate editor.
We should see the following screen. If you’ve run through this before, it will be pre-populated, in which case you can delete row configurations from the hamburger icon.
The Instances section is at the top. Click on the + icon in the valid equivalence class. If you already had an entry, double click it.
You will see the following screen.
Click the dropdown and choose Add New Factory Method from the popup.
You will now see the following screen.
Enter the name of your factory method.
Click on the Add button to create a parameter to pass to the factory method.
Select the type of the parameter.
addSteps(int steps)clearly requires as int.
Specify the name of the factory method argument.
You will be taken back to the previous screen, where you’ll now see our newly configured parameter field
Enter the value you want to initialise
SimpleStepswith, we’ll choose 100.
Press Save and you’ll be back in the main editor. Double-click to modify if you need to.
Generate test cases
Press the Generate Test Cases button. Before we can generate the test code, we need to define the output equivalence classes.
Add a new valid representative. Because addSteps() returns void, DevMate will automatically create the Throws no exception representative for us.
Then press Generate Test Cases.
Generating the code
Click the radio button as shown so the test case is complete.
Press the Generate Test Code button and open the saved file.
Editing our factory method
Unlike Class instantiation with constructor, you’ll need to write the implementation for your new factory method.
Near the top of the file you’ll see the boilerplate for the method that DevMate generated.
All you need to do now is write the implementation that initialises and returns a
In this and the previous tutorial we’ve seen two different ways to initialise an object in DevMate.