Unit test using JUnit in Eclipse

zhaozj2021-02-16  110

How to write test code is definitely the most headache of developers. JUnit is a very powerful unit test package that can be tested for one / multiple classes of single / multiple methods, can also combine different TestCase into TestSuit to automate test tasks.

This article briefly describes how to create a TestCase using Junit in Eclipse to test a simple class.

We write a class Simple to be tested as follows:

Package jexi.test; public class simple {private int n; public simple (int N) {this.n = n;} // Return absolute value: public int foo () {RETURN N> 0? N: (-N) }}

The foo () method returns an absolute value, the next step, we are ready to fully test this foo () method with JUnit.

First, in Eclipse, create a Java project, put the plugins / org.junit_3.8.1 / junit.jar into in:

Then write simple.java, create a JUnit Test Case for it:

Fill in the name of the test class in the pop-up dialog: SimpleTest, hook setup ():

Write test code:

package jexi.test; import junit.framework.TestCase; public class SimpleTest extends TestCase {private Simple s1, s2; protected void setUp () throws Exception {super.setUp (); s1 = new Simple (10); s2 = new Simple (-7); public void testfoo () {asserttrue (S1.foo () == 10); asserttrue (s2.foo () == 7);}}

Where the setup () method is to construct the initialization environment, we create two instances of simple in Setup, testfoo () is used to test the test method of foo (), always constructed with Test method name, and then test in the test method: S1.foo () == 10, if the return value is equal to the expected result 10, asserttrue () will be successful, we can now run run-> run as ...-> junit test, the test results will be displayed on the left:

If we change the simple's foo () method:

Public int foo () {return n;}

Run the JUnit Test again, now Asserttrue (S2.FOO () == 7); the test result is incorrect, JUnit will report which line of the line is incorrect:

Double-click to quickly locate the method call to the test failed.

to sum up:

The JUnit function is very powerful and is a reliable guarantee of code quality. Carefully designed TestCase can be used repeatedly, and will change a class in the future. You only need to run over TestCase to know that the change has no effect on the client. Several TestCase can also be combined into testsuit, combined with ANT makes compiled, test, run throughout the process, and only the code can know which code has a problem.

转载请注明原文地址:https://www.9cbs.com/read-10309.html

New Post(0)