Java in Eclipse and JUnit Tests
Making a Java Workspace (if you are using Eclipse to edit OCaml and Java code)For the Java portion of the course, we recommend creating a new Java workspace, so that you don't have to switch settings between OCaml and Java when you move back and forth. To create a new workspace:
- Click File --> Switch Workspace --> Other ...
- Click Browse... and navigate to the place where you want to store your Java workspace on disk.
- Create a new folder for your Java workspace and select it. Give it a meaningful name like "JavaWorkspace" so that you can find it easily.
Creating a Java Project
- Click File --> New --> JavaProject.
- Give the project a name
- Under "Use an execution environment JRE", make sure that JavaSE-1.8 or JavaSE-8 is selected.
- Click "Next" (not "Finished").
- Under the "Sources" tab, if a "Create module-info.java" box is checked, uncheck it.
- Under the "Libraries" tab, click "Add Library", "JUnit", "Next", select "JUnit 4", and click "Finish".
- Import the homework files into the src folder.
- Right click on src subfolder of project
- Choose Import --> General --> File System --> Next
- Browse to the folder you downloaded with the homeworks files, then select it
- Check the box (so that it is selected) next to the folder, then select Finish
- Select the new test folder in your project, choose Build Path --> Use as Source Folder. (If this is not an option, the test folder is probably a source folder and you don't have to do anything)
Using the Eclipse debuggerFor debugging Java code, the Eclipse debugger can turn out to be more helpful than just using print statements, especially when you start having really complex code. Here are some resources to help you learn how to use the Eclipse debugger:
- CIS 121's YouTube tutorial on how to use the Eclipse debugger
- Chapter 6.10 from Big Java
- Using the Eclipse Debugger for Beginning Programmers
JUnits TestsUnit testing is a method of testing source code that verifies that individual units are working properly. A unit of code refers to the smallest testable part of an application, in Java this corresponds to a method. JUnit is a Java package that implements unit testing. Eclipse provides tools to automate the creation of JUnit tests. It also provides a good interface for running the tests. Together these two tools make systematically testing your program very easy. In this lab we'll learn how.
Creating JUnit Tests
- Right click on your Classname --> New --> JUnit Test Case --> Next.
- Select the methods you want to test. Click "Finish".
- Fill in tests appropriately. See Assert Types for a list of possible asserts.
- To run JUnit Tests, right click on the test class --> Run As --> JUnit Test.