The test framework in the Java programming idea is organized in:
1, first define an interface, only use this interface to provide a meaningful name in the code, representing the state.
package com.jereh;publicinterface InvariantState {}
2. Define two state classes that indicate success or failure, and the failure class object includes an object that represents the reason information about the failure, which is generally intended to display this information.
package com.jereh;public class InvariantOK implements InvariantState{}
PackageCom.jereh; Public class invariantfailure implements invariantstate{ PublicObject value; Public invariantfailure(Object value) { This. value = value; }}
3. Define an interface, and any class that needs to test the constraints must implement this interface:
package com.jereh;publicinterface Invariant { InvariantState invariant();}
4. Define a class and inherit the timer, and automatically end the program after a period of time if no abnormal condition occurs:
PackageCom.jereh;ImportJava.util.Timer;ImportJava.util.TimerTask; Public class Timeout extends Timer{ Public Timeout(intDelayFinalString msg) {Super(true); ScheduleNewTimerTask () { Public void Run() {System.out.println (msg); System.exit (0); }},delay); }}
5. Define a thread, using the invariant interface and the timeout class, to be used as an observer:
PackageCom.jereh; Public class invariantwatcher extends Thread{ PrivateInvariant invariant; Public Invariantwatcher(Invariant invariant) { This. invariant = invariant; Setdaemon (true); Start (); } Public Invariantwatcher(Invariant invariant,Final intTimeOut) { This(invariant);NewTimeout (timeout,"Timed out without violating invariant"); } Public void Run(){ while(true) {Invariantstate state = Invariant.invariant ();if(stateinstanceofInvariantfailure) {System.out.println ("invariant violated:"+ ((invariantfailure) state). value); System.exit (0); } } }}
6. Test the class and put the observer in the target class to be tested:
PackageCom.jereh; Public class evengenerator implements invariant{ Private intI Public void Next() {i++; i++;} Public int GetValue(){returnI }@Override PublicInvariantstateinvariant() {intval = i;if(val%2==0){return NewInvariantok (); }Else{return NewInvariantfailure (NewInteger (Val)); } } Public Static void Main(string[] args) {Evengenerator Gen =NewEvengenerator ();NewInvariantwatcher (gen); while(true) Gen.next (); }}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Java Threading Test Framework