JUnit cookbook (translation)

zhaozj2021-02-17  143

There are some examples to dedicate to you, using JUnit to write and organize your own tests.

Simple test case

How do you write test code?

The easiest way is to write a code in the debugger and modify the debugger without recompilation. Finally, it has to be judged which object is the final run.

At the same time, you can also print the test code as a complete statement to the standard output stream, for example: public class car {public int getWheels () {return 4;}}

// Execute the class public class testcar {public static void main (string [] args) {testcar mytest = new testcar (); mytest.testgetwheels ();} public testGetWheels ();} public testGetWheels ();} public testGetWheels (); int expectedwheels = 4; car mycar = car (); If (expeectedwheels == mycar.getwheels ()) System.out.println ("TEST [CAR]: Getwheels Works Perfected!"); Else System.Out.println ("Test [": getWheels Doesant Work! ");}}

However, both test styles have limitations because they need programmers to judge and analyze the results. Similarly, sometimes I just need to understand a result of debugging code, but sometimes there is too much output stream in a program, resulting in horrible "reel messy". JUnit test does not require programmers to explain, and you can easily perform many tests at the same time. When you need to test, follow the methods:

1. Construct an instance of a TestCase class; 2. Create a constructor to receive the String parameter to access the superclass; 3. Override the RUNTEST () method; 4. When you need to detect the value, call with the Boolean return type method asserttrue ( To determine whether the test is successful.

For example, to test whether the sum of the two Money objects is the same as the predicted value, this is written:

Public void testsimpleadd () {Money M12CHF = New Money (12, "chf"); Money M14CHF = New Money (14, "CHF"); Money Expected = New Money (26, "CHF"); Money Result = M12CHF. Add (M14CHF); asserttrue (expected.equals (result));}

If you need an existing test, just write a fixture instead. Create a Suite when you need to run a lot of tests. FixTure

What should I do if you have more than two to the same group of objects based on similar or identical tests?

Testing will create a set of (to be tested) objects (such as: Money F12CHF, Money M14CHF). This group of objects is called Test FixTure. When you are writing testing, you will often find that you will write fixture more valuable than you actually test. To some extent, creating a FixTure code is easier than the wings that are carefully wing on the constructor. On the other hand, a greater advantage comes from being able to reuse these FixTure code, which often uses the same fixture in various test code. Each case is tested to fixture for information and parameters, you can test different results.

According to this, you can have a public Fixture:

1. Create a subclass of TestCase; 2. Create a constructor that can receive String type parameters, then pass it to the superclass; 3. Add an instance variable for each fixture section; 4. Override the setup () method to initialize the variable Initialize all Test's fixture, even network connections can be established in Setup. 5. TearDown () Releases the permanent resource you assigned in Setup (), such as database connections.

For example, give 12 Swiss francs, 14 Swiss francs, $ 28 different combined test programs, first create a FixTure:

public class MoneyTest extends TestCase {private Money f12CHF; private Money f14CHF; private Money f28USD; protected void setUp () {f12CHF = new Money (12, "CHF"); f14CHF = new Money (14, "CHF"); f28USD = NEW MONEY (28, "USD");}} You can test it with your heart as you want to prepare fixture. Test Case how to write and call a separate test after FixTure?

Test Case to simply replace FixTure, create an anonymous subclass of the TestCase class and override the RUNTEST () method. Establish anonymous subclass for separate tests. You will notice that there are a few such tests to take a lot of row code.

JUnit provides a simpler way, you need this:

1. In the FixTure class, create a test case method, you need to declare as public, otherwise you will not be called by mapping. 2. Create an instance of a TestCase class and pass the name of the Test Case method to the constructor.

For example, Money and Moneybag are additional operations:

Public void testmoneymoneybag () {// [12 CHF] [14 CHF] [28 USD] == {[26 CHF] [28 USD]} Money Bag [] = {F26CHF, F28USD}; Moneybag Expected = New Moneybag (BAG); Assertequals (expected, f12chf.add (f28usd.add (f14chf)));

Create a Moneytest instance and run Test Case: New Moneytest ("TestmoneyMoneybag")

When testing run, various test methods will be automatically detected and run. Once you need to perform a few tests, you need to organize them in Suite. Suite

How to implement multiple tests in one time?

When you have multiple tests in your hand, the first reaction will try to test them together, which will be simpler. Before this, you will test alone one by one until you feel tired. Then now Junit provides an object - TestSuite, which can put a lot of tests together.

For example, a single test is like this: TestResult results = (New Moneytest ("TestMoneyMoneybag")). Run (); integrated test of two cases, like this:

Testsuite Suite = new testsuite (); suite.addtest ("TestMoneyEquals")); Suite.Addtest (New Moneytest ("TestsImpleAdd")); TestResult Result = suite.run ();

Another way is to let Junit extract Suite from TestCase. This will pass the TestCase class to the TestSuit constructor. TestSuite Suite = New Testsuite; TestResult Result = Suite.Run ();

The subset of multiple test cases contains the subset of the plurality of test cases into Suite, and Suite will automatically select the best solution. It avoids re-update Suite code caused by new test cases.

TestSuite not only contains TestCase, but also contains other objects that meet Test interfaces. For example, you can create a TestSuite in your code, you can also include them in my code:

Testsuite Suite = new testsuite (); suite.addtest (kert.suite ()); suite.addtest (Erich.suite ()); test result = suite.run (); Testrunner

How can I test their results?

You can create a Test Suite before you can create it. JUnit provides numerous tools to define Suite and execute and display results. The integrated test and Testrunner tool can be combined with a static method Suite () and return to Test Suite. Public static test suite () {testsuite suite = new testsuite (); suite.addtest ("TestMoneyEquals"); Suite.Addtest (New Moneytest ("TestsImpleAdd"); Return Suite;}

If a TestCase class cannot define Suite () methods, Testrunner will extract Suite and fill the method starting with "TEST". JUnit also provides two interfaces for Testrunner, enters Java junit.awtui.teStrunner or junit.swingui.teStrunner, the graphical user interface will appear:

1. Select the appropriate item in the input box. In the case of failure, Junit will perform the wrong list below, JUnit will distinguish it is Failures or Errors. Failure refers to the result and assertion (Assertion) is inconsistent, and the error refers to an exception such as ArrayIndexOutofboundSexception. As shown below: "Hot Code Update" supports "Hot Code Update" supported by VisuaLage in a dynamic programming environment, you can always use the junit window. Others do not support this feature, you can also turn off the JUnit window to open again, but this is very monotonous and wasting time. One choice is to use Junit's AWT and SWING interface junit.Runner.LoadingTestCollector. LoadingTestCollector will reload the test class when different tests. If this feature is used, the "RELOAD CLASSES EVERY RUN" button will be inequential.

JUnit has a series of interfaces that run Java Junit.Textui.Testrunner at the command prompt, and add a class with the Suite method. Then output in text interface, the choice is to call the defined main method in the TestCase class.

For example, run Moneytest: Public Static void main (String Args []) {junit.textui.teStrunner.Run (Suite ());

By defining the main method, simply enter Java MoneyTest in the command prompt. Of course, no matter the graphical interface or text interface, you must confirm that the junit.jar file is in your classpath. (Please pay attention! Quote, transfer this article to note: rosen Jiang and the source: http://blog.9cbs.net/ROSEN

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

New Post(0)