Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java Unit Testing in Java How to Test Using Before to not repeat yourself

Created Calculator object in @Before (setup) method, but compiler says it doesn't recognize it in individual test cases

Hello. I've created a Calculator object by adding the line Calculator calculator = new Calculator() in the setup method for this exercise, but when I preview or submit the code, it gives me this compiler error:

symbol: variable calculator location: class CalculatorTest ./com/example/CalculatorTest.java:24: error: cannot find symbol int answer = calculator.addNumbers(1);

Am I creating the new Calculator incorrectly within the setup method, or is it just not running correctly somehow?

com/example/CalculatorTest.java
package com.example;

import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.*;

public class CalculatorTest {

    @Before
    public void setUp() throws Exception {
        Calculator calculator = new Calculator();
    }

    @Test
    public void addingMultipleNumbersProducesResult() throws Exception {
        int answer = calculator.addNumbers(1 ,2, 3);

        assertEquals(6, answer);
    }

    @Test
    public void addingSingleNumberTotalsAppropriately() throws Exception {
        int answer = calculator.addNumbers(1);

        assertEquals(1, answer);
    }
}
com/example/Calculator.java
package com.example;

public class Calculator {

    public int addNumbers(int... numbers) {
        int total = 0;
        for (int number : numbers) {
            total += number;
        }
        return total;
    }
}

1 Answer

Alexander Nikiforov
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Alexander Nikiforov
Java Web Development Techdegree Graduate 22,175 Points

You've created calculator inside setUp method, that is why it is ONLY available in setUp method.

In order for it to be available in all tests, you have to declare it as member of a test class.

Does it makes sense ?

If not please re-watch previous video, and see how Craig defines Creditor creditor

Thank you