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){ //TODO 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.
Use:
- + to add
- – to subtract
- / to divide
- * to multiply
Example:
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
@Test 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!
Reblogged this on Potato Coding Adventure.
LikeLike