Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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?

package com.example;

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

import static org.junit.Assert.*;

public class CalculatorTest {

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

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

        assertEquals(6, answer);

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

        assertEquals(1, answer);
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
.a{fill-rule:evenodd;}techdegree seal-36
Alexander Nikiforov
Java Web Development Techdegree Graduate 22,161 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