Unit Testing of Classes in Java

Every class can have a main method. That is a handy trick for unit testing of classes. For example, you can add a main method to the Employee class:

test.java :

import java.util.*;
import java.time.*;

class Employee
{
	String name;
	double salary;
	LocalDate hireday;

	public Employee(String n, double s, int year, int month, int day)
	{
		name = n;
		salary = s;
	}

	public static void main(String[] args)
	{
		Employee e = new Employee("Romeo", 50000, 2003, 3, 31);
		System.out.println(e.name);
	}
}

After compilation javac test.java:

If you want to test the Employee class in isolation, simply execute

java Employee

If the Employee is a part of a larger application, you start the application with

java Application

and the main method of the Employee class is never executed.

这个方法可以用来调试Java子程序和Class,而不用每次都新建一个完整的Application。

posted @ 2017-06-28 11:15  2021年的顺遂平安君  阅读(24)  评论(0编辑  收藏  举报