Testing Java code with JUnit

Source: Internet
Author: User

Junit Unit test Lab report first, the experimental environment

MyEclipse2014,Junit4.10

TwoExperimental Purpose

Learn unit tests and perform Junit tests in myeclipse

ThreeExperimental Steps1.write the class you want to test

The code is as follows:

Package com.cheng.test;

Public class Calculate {

Public int Add (int A,int b) {

return a+b;

}

Public int Sub (int A,int b) {

return a-2*b; Bug The calculation subtraction should be a-B;

}

Public int divide (int A,int b) {

return A/b;

}

Public int mul (int A,int b) {

return a*b;

}

}

2.add junit4.10.jar

After adding junit4-10 , the file directory is as follows:

3.new test class for testing previously written classes

The directory structure is as follows:

The test class code is as follows:

Package com.cheng.test;

Import static Org.junit.Assert. assertequals;

import Org.junit.Before;

import org.junit.Test;

Public class testcalculate {

Calculate Cal;

@Before

Public void setUp () {

Cal = new Calculate ();

}

@Test

Public void Testadd () {

assertequals  ("Additive Problem", 5,cal.add (2,3)); Test addition is correct

}

@Test

Public void testsub () {

assertequals ("Subtraction Problem", 8,cal.sub (10, 2));

}

@Test

Public void Testmul () {

assertequals ("Multiplication Problem", 20,cal.mul (10, 2));

}

@Test

Public void Testdiv () {

assertequals ("Problem with Division", 5,cal.divide (10, 2));

}

}

4.run junittest

Bundle test results to find the previous bug, modify the source code in the SRC folder, run junittest again

Add part Modified code :

Public int Sub (int A,int b) {

return A-B; Before is a-2*b; The calculation subtraction should be a-B;

}

Testing Java code with JUnit

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.