Going up: let’s write some code!

In your Calculator project you have two java files:

  • Calculator.java in src/main/java where you will write the calculations
  • CalculatorTest.java in src/test/java that you will use to test the code written in Calculator.java

Write some code

Open Calculator.java.

You can see a code needed to write some functions of the calculator inside: add, subtract, multiply etc.

public class Calculator {
    public int add(int summand1, int summand2){
        return 0;

It is your calculator. It has different things to do but now every arithmetical operation returns 0 (every operation the calculator does gives you 0).

I’d like you to change every 0 in the code for add, subtract, multiply and divide to return proper operation.


  • + to add
  • to subtract
  • / to divide
  • * to multiply


    public int add(int summand1, int summand2){
        return summand1+summand2;

Test your code

To check if your operation returns a proper value you can test it using CalculatorTest.java. 

Open CalculatorTest.java.

You can see there

public void sum() {
    Assert.assertEquals(3, (new Calculator()).add(1, 2));

@Test tells you that public void sum() is a test.

Inside you have a code that will check if the code you wrote in Calculator.java returns (gives back) correct value. For example, for add(1, 2) it should be 3.

To run the test code right click on the name sum() and choose Run as > JUnit test


If you did this before writing a code you’d got something like this (JUnit tab opened under Java code – I moved mine to the right -> drag and drop):


If you wrote the code before running the test for sum() you probably have something like this:


You can also run the test for the whole file.

Right click on:

  • the file name in the project explorer or
  • on the CalculatorTest text in Java file or
  • anywhere in the Java file

Then choose Run as > JUnit test. Before you implement all the code you’ll get:


After you implement the code properly all tests will be green 🙂


Since I’ve asked you to finish only four basic calculator functions you’ve probably got something like this:


We’ll make next tests pass soon!

One thought on “Going up: let’s write some code!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s