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

Derek Derek
Derek Derek
8,744 Points

java simple tests

Hello,

I have written a java code that uses methods of string.indexOf() and string.charAt(). I am trying to write a test for this code, but I am not sure how to approach it.. First of all, I keep getting "error: package org.junit does not exist" when trying to compile my test code..

Can someone please take a look and tell me how to do a test for this code? I have attached my java code as well as my attempt for a test.. Thank you!

public class Method {

    public static String mSampleString = "Hi, my name is Anonymous.";

    public static void main(String[] args) {
        String s = mSampleString;
        changeString(s);
    }

    public static void changeString(String s) {
        System.out.println(s.indexOf("n"));
        System.out.println(s.charAt(1));

    }
}
package method;

import org.junit.Test;
import static org.junit.Assert.*;


public class MethodTest {

    public static String mSampleString = "Hi, my name is Derek.";

    public static void main(String[] args) {
        Method m = new Method();
        testMethod();       

    }

    @Test
    public static void testMethod() throws Exception {
        assertEquals("i", mSampleString.charAt(1));
                assertEquals(5, mSampleString.indexOf("m"));
    }
}

[MOD: edited code block]

1 Answer

Plamen Neshkov
Plamen Neshkov
18,236 Points

You need to add JUnit to your classpath. Depending on your IDE, you can find instructions in the appropriate documentation.

IntelliJ IDEA

Eclipse

Derek Derek
Derek Derek
8,744 Points

I use sublime text 2 though..

Plamen Neshkov
Plamen Neshkov
18,236 Points

You should consider switching to an IDE for Java, as it makes your life much easier. You should understand how an IDE works under the hood as well, though.