In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/03 Report--
This article focuses on macro CI and unit testing techniques. Some technical details will be skipped. For more details, please refer to the "Resources" in the last part and the links in the article.
Author: du Mingtan
This paper includes five parts: continuous integration, unit testing, Mock technology, Case selection strategy and examples.
Continuous integration (CI)
CI is a practice designed to ease and stabilize the building process of software that addresses the following challenges:
Software build automation continuous automatic build check continuous automatic build testing (the focus of this article) automation of the subsequent process of build generation
For details, please see:
Http://www.javaworld.com/javaworld/jw-12-2008/jw-12-hudson-ci.html
Hudson and its construction
A very popular CI tool, easy to install and configure, low learning cost. In this article, hudson installation and configuration is carried out on the windows platform.
Install JDK
Download the installation directly from www.java.com, and then set the java-related environment variables:
JAVA_HOME:jdk installation directory, for example: C:\ java\ jdk1.7.0
PATH: enables the system to recognize the java command in any path, set to:% JAVA_HOME%/bin;%JAVA_HOME%/jre/bin
CLASSPATH: load the class or lib path for java. The java command will recognize it only if the class is in classpath. Set to:.% JAVA_HOME%/lib/dt.jar;%JAVA_HOME%/lib/tools.jar (to add. Represents the current path)
Install ANT
Download ant1.8.2 from http://ant.apache.org/
Extract to any directory and set the environment variable ANT_HOME to point to the ant home directory
Set the environment variable ANT_OPTS with a value of-XX:MaxPermSize=128M-Xms128M-Xmx512M to allocate more memory space
Install Hudson
First download hudson.war http://www.hudson-ci.org/
Second, run through the java-jar hudson.war command
Because of the built-in http service, open http://localhost:8080 in the browser to see if hudson is running
Continuous operation method
Concise usage
Add nodes and set them
Can be understood as a project, the following is admaker as an example. For more nodes, please click "New Node"
Node settings, mainly set "Remote FS root" and "Launch Method".
Add job and set it
It can be understood as a task of creating a project. The example is auto. You can use the following options:
Integrated flexunit/pmd/cpd
Hudnson compiles automatically through ant, and sets the compiled result as the read source of hudson. The operation principle is as follows:
Automatic compilation settings
Copy the flexTasks.jar under sdk\ x.x.x\ ant\ lib to the ant\ lib directory and specify it in build.xml with the following directive:
File settings required for unit testing
Download the source code from https://github.com/flexunit/flexunit, compile it automatically through ant, generate a file similar to flexUnitTasks-4.1.0-x.jar, copy it to the libs folder where the project is located, and specify it in build.xml with the following directive:
"
PMD/CPD
Flexpmd is mainly used to improve the quality of code in Flex/AS3 source files and to detect common bad code practices, such as useless code, inefficient code snippets, overly complex code, etc. These are all objects that FlexPMD detects and reports.
Code repetition rate check tool in flexcpd,Flex/as3 source file. Download the files needed to compile with ant. The latest version is 1.2: http://opensource.adobe.com/wiki/display/flexpmd/Downloads.
Configuration (flexpmd): http://opensource.adobe.com/wiki/display/flexpmd/How+to+invoke+FlexPMD
Configuration (flexcpd): http://opensource.adobe.com/wiki/display/flexpmd/FlexCPD
The method of conditional compilation parameters
Add the following in the flex-config.xml file:
CONFIG::debugfalseCONFIG::embedfalseCONFIG::edittrue
Construction
Click "Build Now" to see the corresponding results.
The problem that default port 1024 is occupied under windows
The property port in is the port number that specifies the socket server, while the default port number in CIListener is 1024. What you need to do at this time is:
Change the default port number in CIListener.as and VisualDebuggerListener.mxml to 9900, perform ant compilation in the flexunit project directory, find the flexunit-cilistener-41.0-1-4.5.0.0.swc file in FlexUnit4Test\ libs, and put it in the appropriate place in your project. At this time, you should pay attention to display the specified port= "9900".
In order not to display the specified port number 9900, change the default port number to 9900 in TestRunConfiguration.java, perform ant compilation in the flex project directory, find the flexUnitTasks-4.1.0-1.jar file in FlexUnit4Test\ libs\ build, and put it in the appropriate location of your project. It is recommended to complete the operation of the above two steps
Unit testing
Flexunit4
Evolutionary history
As2unit 2003
Flex1.0 flexunit
Flex2.0 flexunit.9 as3- > as3flexunit (google code)-- > back to adobe
DpUInt- > Fluint
Flexunit4 2009
Frame schematic diagram
Usage
Right-click on the project, add test case or test suite (for case package, including n case), add the corresponding file, and flash builder will automatically create the main test class FlexUnitApplication.as for you
Right-click "execute Unit Test" on the project or execute it through the unit test panel, and select the appropriate test case or test suite to run.
The general structure is as follows. AM2Test can be used as the only entrance:
Basic knowledge
TestMethod,testCase,testSuite
The structure diagram is as follows:
TestMethod
The smallest test unit, as its name implies, uses the [Test] meta tag for testing methods of a class, as shown in the following example:
[Test] public function testUpload () {}
Strategy:
It is common to write at least one testMethod for each method in the class
For a method, because different conditional logic may produce different results, write a testMethod for each result
For no method, write two testMethod for valid and invalid input
TestCase
A collection of testMethod to test multiple related function points, usually for a certain class, which contains all the testMethod to be tested, including the following unique metadata tags, which can be written repeatedly:
[Before] [Before Class] [After] [After Class] [Test]
Each of these [Test] can be ordered, specified by the order attribute, such as:
[Test (order=1)] public function testOrder1 () {}; [Test (order=2)] public function testOrder2 () {}; TestSuite
A collection of testCase, marked with metadata tags such as the following. Examples are as follows:
[Suite] [RunWith ("org.flexunit.runners.Suite")] public class MultiFileUploaderSuite {public var _ testUploadList:TestUploadList;}
Assertion
Assertions are used to compare the results and expected values of the test target in the following format:
Assert (error prompt, expected value, actual value)
Example:
Result = 1 + 2
AssertEqual ("result is not 3", 3, result)
There are two formats to use:
Hamcrest
Open source matchmaker library in the following format:
AssertThat (value, matcher)
Where matcher is a class, such as is (), between (), closeTo (), etc.
Examples of usage:
AssertThat (num1, is (between (num2, num3))
Custom matcher:
Import org.hamcrest.TypeSafeMatcher;import org.hamcrest.Description;public class myMatcher exends TypeSafeMatcher {public function myMatcher () {}; override public function matchesSafely (item:Object): Boolean {}; override public function describeTo (description:Description): void {};}
For more information, see http://github.com/drewbourne/hamcrest-as3
Asynchronous test
The core function of flexunit4, think of the various asynchronous events in flash! Contains two formats, event handling and event sequence (sequence).
Sample code for event handling:
[Test (async, timeout=5000)] public function testCancel (): void {var mHandler:Function = Async.asyncHandler (this, cancelHandler,5000, {num:4,type: "m"}, timeoutHandler); _ uploader.addEventListener (UploaderEvent.EVENT_FILE_ALL_MEMEORY,mHandler); _ uploader.loadtoMemory ();}
As shown in the example:
Async: must exist, indicating that it is an asynchronous test
Timeout=5000, the test is not completed within 5000 milliseconds, default timeout handling
MHandle is an asynchronous processing object, which contains five parameters. The meaning is as follows:
This: for which TestCase, this is this
CancelHandler, the event object triggered after receiving the UploaderEvent.EVENT_FILE_ALL_MEMORY event
5000, the maximum time for timeout processing to trigger
{num:4,type: "m"}, the parameter passed to the cancelHandler object
TimeoutHandler, timeout processing object, cancelHandler object trigger is not triggered after 5000ms
For more information, please see: http://docs.flexunit.org/index.php?title=Writing_an_Async_setup#Approach
Event sequence is a very practical format to use, such as testing a file upload process to cancel the function, will trigger events are upload, cancel successfully, cancel failure, and so on, at this time if written in the format of event handling, then n processing functions will be involved, very complex, and with sequence, obviously clear at a glance.
Sample code for event sequence:
[Test (async)] public function shouldCompleteTimerSequence (): void {var timer:Timer = new Timer (TIMEOUT); var sequence:SequenceRunner = new SequenceRunner (this); sequence.addStep (new SequenceCaller (timer, timer.start)); sequence.addStep (new SequenceWaiter (timer, TimerEvent.TIMER, TIMEOUT2)); sequence.addStep (new SequenceWaiter (timer, TimerEvent.TIMER, TIMEOUT2); sequence.addStep (new SequenceWaiter (timer, TimerEvent.TIMER, TIMEOUT2); sequence.addStep (new SequenceCaller (timer, timer.stop); sequence.addAssertHandler (handleSequenceComplete, null)) Sequence.run ();}
As shown in the example, the steps are as follows:
Start a timer
Loop three times
Stop timer
Execute assertion
For more information, please see: http://docs.flexunit.org/index.php?title=Fluint_Sequences
Rules
Metadata tags similar to [Before] and [After] provide more advanced features, define rules before and after each test, and run before and after each test. The structure is as follows:
-BeforeClasses
-Rules
-Befores
-Test
-Afters
-Rules (the same ones as above)
-AfterClasses
UIImpersonator
Draw lessons from the test content display object of the Fluint framework, through which you can temporarily put the visual content on the stage, in fact, I think it is not very practical, which is contrary to the idea of automation. It cannot be displayed in pure as3 projects for the time being, but you can use this technique to achieve: https://gist.github.com/1094408
For more information, see http://docs.flexunit.org/index.php?title=UIImpersonator
Runner and Custom Runner
Specify the behavior of Test Method, Test Case and Test Suite runtime, good compatibility, can run well the test content of flexunit1 and fluint framework. For Runner with different responsibilities, the most common one is Suite. When the test unit runs, the Cla***equest object is wrapped into an IRequest object based on the contents of each Test Case and Test Suite, and building a corresponding Runner,FlexUnitCore.run for this object (Cla***equest) executes all IRequest objects, triggers the run () method of the IRequest, and executes the corresponding Runner.run (). The Runner customized by the system is:
IgnoredCla***unnerSuiteTheoryBlockRunnerSuiteMethodFlexUnit1Cla***unnerFluint1Cla***unnerBlockFlexUnit4Cla***unnerParentRunner
To customize Runner, you can implement the following methods:
Import org.flexunit.runner.IDescription;import org.flexunit.runner.IRunner;import org.flexunit.runner.notification.IRunNotifier;import org.flexunit.token.IAsyncTestToken;public class CustomRunner implements IRunner {public function CustomRunner () {} public function run (notifier:IRunNotifier,previousToken:IAsyncTestToken): void {} public function get description (): IDescription {} public function pleaseStop (): void {}}
For more information, see http://docs.flexunit.org/index.php?title=Custom_Runners
UIListener
The listening object of Runner, which is used to graphically represent the listening content. The process is as follows:
Import sampleSuite.SampleSuite;import org.flexunit.listeners.UIListener;import org.flexunit.runner.FlexUnitCore;private var core:FlexUnitCore;public function runMe (): void {core = new FlexUnitCore (); core.addListener (new UIListener ()); core.run (sampleSuite.SampleSuite);} CIListener
The listening object of Runner does not need to be represented graphically. It is said that all you need to do is to send the listening content to the server through Socket, and write the content to disk for Hudson to read and process. The process is as follows:
Core.addListener (new CIListener ())
Core.run (sampleSuite.SampleSuite)}
Mockolate
Principle
Object, containing all the public methods and properties of the original object, and the parent class of the mock object is the original object class, so that the mock object can be used where the original object is used.
Since mock technology is an independent technology, I will not elaborate on it here. Please refer to: http://www.mockolate.org/
Use
Custom Runner, custom Rule, and Mock tags:
[RunWith ("mockolate.runner.MockolateRunner")] public class TestUploader {[Rule] public var mocks:MockolateRule = new MockolateRule (); [Mock (type= "strict")] public var fileReference:FileReference; [Mock (type= "strict")] public var fileReferenceList:FileReferenceList;}
As shown above, use MockolateRunner when running the TestCase, customize the MockoateRule, specify the class to be mock through the Mock tag, and specify the strict mode.
The next thing to do is to use them in TestMethod:
Var frl:FileReferenceList = strict (FileReferenceList); mock (frl). Getter ("fileList"). Returns ([]); mock (frl). Method ("toString"). Returns ("FileReferenceList"); mock (frl). Method ("browse"). Args (Array). Dispatches (new Event (Event.SELECT, false, false); _ uploader.fileReferenceList = frl
As shown above
The getter method fileList returns as a []
The toString () method returns "FileFeferenceList"
When you call the browse () method, you specify a parameter of type Array and dispatch the SELECT event.
Finally, the Mock object is passed to the _ uploader object by _ uploader.fileReferenceList = fr1.
Case selection strategy
For interfaces, but not for getter/setter methods
Core function points, such as upload, interrupt and other functions in the upload module
Function points with complex logic, if-else, switch-case, etc.
For function points, it is possible to combine functions. In the case of limited time, non-core function points can be omitted.
Write case according to bug, reproduce the steps, and verify it
Not for style and presentation and other related function points, for example, "when the file name is 20 Chinese, the upload list displays incorrectly", should be fully guaranteed by QA, belongs to the scope of non-single test.
Before the single test begins, the developer should communicate with QA to confirm which case is guaranteed by QA and which case is guaranteed by the developer.
Sample display
Take the core multi-file upload class Uploader as an example. To test this class, you must use mock technology, because the data of FileReference is read-only.
According to the selection strategy, finally lock in the core method of the Uploader class, and establish the following case:
TestUploadedToMemory () testUploadedALLComplete () testUploadedALLError () testCancel () testResume () testDelete ()
Each case mock FileReference, FileReferenceList, and the core class AMFPHP used to communicate with the AMF backend
The example code for testCancel () is as follows:
/ * cancel the upload. After two uploads are completed, cancel to verify whether the value of the uploaded ID list is 2percent / [Test (async, order=4)] public function testCancel (): void {_ count = 0 * * mockFileReference (); mockAMFPHP (true); var mHandler:Function = Async.asyncHandler (this, cancelHandler, 5000, {num:4,type: "m"}, timeoutHandler); _ uploader.addEventListener (UploaderEvent.EVENT_FILE_ALL_MEMEORY, mHandler); _ uploader.addFileType ("test") Mock code for _ uploader.browse ();} FileReferenceHeFileReferenceList: / * * mock reference-related classes * * / private function mockFileReference (): void {var frl:FileReferenceList = strict (FileReferenceList); var num:int = 4 var num:int arr:Array = []; for (var imock int; I
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.