Use JUnit to write test cases in eclipse

Source: Internet
Author: User
Tags assert



Eclipse comes with the JUnit plug-in, which makes it easy to write test cases in a project without having to install them.


Add a JUnit library to your project


Before you can write test cases, you need to introduce JUnit first. Right-click on the project root, select Properties,java Build path,libraries,






Add Library, select JUnit:






Click Next to select the JUnit version, then finish is introduced.


Writing test Cases


Suppose you have the following classes:



package choon.test;

public class Calculate {
	public int  Add(int x,int y) {
		return x + y;
	}
}


You can write test cases as follows:



package choon.test;

import static org.junit.Assert.*;

import org.junit.Test;

public class Test1 {

	@Test
	public void test() {
		Calculate calculate = new Calculate();
		assertEquals(8, calculate.Add(3, 5)); 
	}
	
}


Right-click Run as Junit test on the test method so that it runs:






, the green status bar indicates that the test passed, and if it is red, it does not pass.


Before and after tags


The method marked by before runs before each test case executes, and is run after each test case execution by the after-tagged method.



If you write the following test case:



package choon.test;

import static org.junit.Assert.*;

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

public class Test1 {
	@Before
	public void setUp() {
		System.out.println("---begin test---");
	}
	
	@Test
	public void test() {
		Calculate calculate = new Calculate();
		assertEquals(8, calculate.Add(3, 5));
		System.out.println("test case");
	}
	
	@After
	public void tearDown() {
		System.out.println("---end test---");
	}
}


The following results will be executed:






It is important to write test cases, a bad test case is not a test and a waste of time, and a good test case can be very good to point out the problem in the code, to avoid greater trouble.


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.