JUnit Software Testing Technology (tools)
Build the package structure of the specialized user tests in the project.
In JUnit, with @test annotations, you can run a method (mouse over the name of the method you want to run, right-click, select Run as, and then select JUnit test).
The advantage of this is that you do not have to add test code to the main code to avoid the redundancy of the code. and a test class, you can test many functions, do not need the main method.
A. JUnit Note description
The following conditions should be met when using @test annotations:
1) must be a non-static method with no parameters.
2) to add a class with @test annotations, you must have a public construct with no parameters
Package Junit.test;import Org.junit.test;import JUnit. Userdaoimpl;public class Testuserdaoimpl {@Testpublic void testFun1 () {new Userdaoimpl (). FUN1 ();} @Testpublic void TestFun2 () {new Userdaoimpl (). fun2 ();} @Testpublic void TestFun3 () {new Userdaoimpl (). FUN3 ();}}
Second, JUnit test sample Demo
1. After the run is complete, you can see the time and result information that was used to run on the JUnit window.
2. The running results of the tested program appear on the console.
Iii. other annotations in JUnit
@BeforeClass, @AfterClass, @Before, @After
Package Junit.test;import JUnit. Userdaoimpl;import Org.junit.afterclass;import Org.junit.beforeclass;import Org.junit.test;public class TestUserDaoImpl2 {static Userdaoimpl obj = null, @Testpublic void TestFun1 () {obj.fun1 ();} @BeforeClasspublic static void init () {obj = new Userdaoimpl (); System.out.println ("111111111111");} @Testpublic void TestFun2 () {obj.fun2 ();} @Testpublic void TestFun3 () {obj.fun3 ();} @AfterClasspublic static void Finish () {obj = null; SYSTEM.OUT.PRINTLN ("clearing ....");}}
Results: 111111111111
Fun1 ...
8787
Fun2 ...
Fun3 ...
Clearing ....
annotations (Annotation)
I. Meta data
The so-called meta-data is data data. In other words, metadata is descriptive data. Just like the fields in a data table, each field describes what the data under this field means.
Metadata can be used to create documents, track dependencies in code, and even perform basic compile-time checks. Many metadata tools, such as Xdoclet, add these capabilities to the core Java language, temporarily becoming part of the Java programming functionality.
In general, the benefits of metadata fall into three categories: documentation, compiler checking, and code analysis. Code-level documents are most often referenced. Metadata provides a useful way to indicate whether a method depends on other methods, whether they are complete,
Whether the class must reference another class, and so on.
Ii. What is an annotation
Annotations in Java are metadata for Java source code, meaning that annotations are used to describe Java source code. The basic syntax is: the name after the @ followed by the annotation.
iii. predefined annotations in Java (three scheduled annotations in the Java.lang package)
①override: A method that identifies whether a method overrides its parent class correctly.
②deprecated: It is not recommended to use this class member. It is a markup annotation.
③suppresswarnings: Used to suppress warning messages.
Iv. Custom Annotations
The syntax for custom annotations is simple, similar to defining an interface, except that it is preceded by a name with the @ symbol.
1, the simplest custom annotations
<span style= "FONT-SIZE:14PX;" >public @interface Myanno {}</span>
2. Use this annotation
<span style= "FONT-SIZE:14PX;" > @MyAnnopublic class usermodel{} </span>
3. Add members to annotations
<span style= "FONT-SIZE:14PX;" >//defines public @interface Myanno {public String schoolname ();} </span>
<span style= "FONT-SIZE:14PX;" >//using @myanno (schoolname= "People's Republic of China") public class usermodel{} </span>
4. Set Default values
<span style= "FONT-SIZE:14PX;" >//defines public @interface Myanno {public String schoolname () default "People's Republic of China";} </span>
<span style= "FONT-SIZE:14PX;" >//using 1@myannopublic class usermodel{}</span>
<span style= "FONT-SIZE:14PX;" >//using 2@myanno (schoolname= "Java Master") public class usermodel{}</span>
v. Annotations to annotations
☆ Specify target targets
Before you know how to use target, you need to recognize another class, known as ElementType (through the API for detailed learning), which is actually an enumeration. This enumeration defines the different program elements that the annotation type can apply.
<span style= "FONT-SIZE:14PX;" > @Target ({elementtype.type, elementtype.method}) </span>
☆ Set the Retention of retention
Retentionpolicy (detailed learning via API) defines 3 annotation retention in the enumeration class, which determines how the Java compiler handles annotations.
☆ Add public Document documented
The annotations are ignored by default when you use Javadoc to automatically generate documents. If you want to include annotations in your document, you must use documented to annotate the document.
☆ Set Inheritance inherited
By default, annotations of the parent class are not inherited by the quilt class. If you want to inherit, you must add inherited annotations.
Package Annotation;import Java.lang.annotation.documented;import Java.lang.annotation.elementtype;import Java.lang.annotation.inherited;import Java.lang.annotation.retention;import Java.lang.annotation.RetentionPolicy , import Java.lang.annotation.Target, @Inherited @documented@retention (retentionpolicy.runtime) @Target ({ Elementtype.method, Elementtype.type}) public @interface Myanno {public String schoolname () default "haha university";}
Vi. How to read annotations
To read the contents of an annotation, you need to use the technique of reflection. Note: To use reflection to get comment information, you need to annotate with @retention (Retentionpolicy.runtime).
Import java.lang.reflect.*;p Ublic class Testmyanno {public static void Main (string[] args) throws Exception { Class C = Class.forName ("Anno. Usermodel "); Boolean flag = C.isannotationpresent (myanno.class); SYSTEM.OUT.PRINTLN (flag); if (flag) { Myanno ma = (myanno) c.getannotation (myanno.class); System.out.println ("school Name: = =" +ma.schoolname ()); After the data has been obtained, you can begin processing it.}}
class Loader
Multiple ClassLoader can be installed in a Java Virtual machine, the system defaults to three main class loaders, each class is responsible for loading the class at a specific location: BootStrap, Extclassloader, Appclassloader
The ClassLoader is also a Java class, because the class loader of the Java class itself is also loaded by the ClassLoader, and it is clear that the first ClassLoader is not a Java class, which is exactly what Bootstrap
All Class loaders In a Java Virtual machine are organized in a tree structure with a parent-child relationship, when each class loader object is instantiated, a parent class loader object is specified for it, or by default the System class loader is the parent class
Plus download.
I. Parent-child relationship and jurisdiction map between class loaders
second, the class loader's delegation mechanism (through API Understanding ClassLoader Class)
When Java virtual machines load a class, what kind of loader does it send to load?
The class loader of the current thread is first loaded to load the first class in a thread. If Class A refers to a class B,java, the virtual machine uses the class loader that loads class A to load Class B.
You can also call the Classloader.loadclass () method directly to specify a class loader to load a class.
Each class loader loads a class and then delegates it to its parent class loader. When all ancestor class loaders are not loaded into the class, go back to the initiator ClassLoader and still not load, then throw classnotfoundexception, not to find the initiator class plus
The son of the carrier, because there is no Getchild method, even if there is, there are many sons, to find which one?
For the class loader hierarchy diagram and delegate loading principle, explains the reason why the result of the operation was extclassloader after the classloadertest was previously exported to the Itcast.jar package in the Jre/lib/ext directory.
Package Loader;import Org.junit.test;public class Demo {@Test //view class loader public void TestLoader0 () throws Exception { Class C = class.forname ("loader. Person "); ClassLoader loader = C.getclassloader (); APPCLASSLOADER--JAVASYSTEM.OUT.PRINTLN (loader); loader = Loader.getparent (); Extclassloader--javasystem.out.println (loader); loader = Loader.getparent (); Null BootStrap--csystem.out.println (loader);} @Test //ClassLoader public void TestLoader1 () throws Exception {//appclassloader can only load classes in the Project Class C = Class.forName ("loader. Person "); Object obj = C.newinstance (); System.out.println ("obj:" +obj); Class C2 = Class.forName ("D:/ex/usermodel.class");//This is a class outside the project, so it will error object OBJ2 = C2.newinstance (); System.out.println ("Obj2:" +obj2);} @Testpublic void TestLoader2 () throws Exception{hello h = new Hello (); System.out.println (h); System.out.println (H.getclass (). getClassLoader ());}}
Practiceone, to do their own class loader
The core of the virtual machine is to load the. class file through the ClassLoader and perform the corresponding parsing. Then we can do the class loader by ourselves and load the required. Class manually for parsing execution, which extends the functionality of the virtual machine.
The following is excerpted from the API documentation: applications need to implement ClassLoader subclasses to extend the way that Java virtual machines load classes dynamically.
The network ClassLoader subclass must define methods Findclass and loadClassData to implement the load class from the network. After you download the bytes that make up the class, it should use method DefineClass to create the class instance.
Myclassloader.java
Package Loader.myclassloader;import Java.io.bytearrayoutputstream;import Java.io.fileinputstream;import Java.io.ioexception;import Java.io.inputstream;public class Myclassloader extends Classloader{public class FindClass ( String name) { byte[] b=null;try {b = loadclassdata (name);} catch (IOException e) {e.printstacktrace ();} return defineclass (null, b, 0, b.length); } Private byte[] loadClassData (String filename) throws IOException {InputStream in = new FileInputStream (fileName); byte[] B = new byte[1024]; Bytearrayoutputstream out = new Bytearrayoutputstream (), int len=0;while ((Len=in.read (b))!=-1) {out.write (B,0,len);} Out.close (); b = Out.tobytearray (); return b;}}
Testmyclassloader.java
Package Loader.myclassloader;import Java.lang.reflect.method;import Loader. Hello;import Org.junit.test;public class Testmyclassloader {/* * Demo uses our own ClassLoader to load classes outside the project, and can see that the loader for that class is our own */@ testpublic void Testloader () throws Exception{myclassloader loader = new Myclassloader (); Class clazz = Loader.findclass ("D:/ex/hello.class");//class clazz = Loader.findclass ("D:/ex/usermodel.class"); Object obj = Clazz.newinstance (); System.out.println (obj); System.out.println (Obj.getclass (). getClassLoader ()); Loader.myclassloader.myclassloader}//[email protected] @Testpublic void TestLoader2 () throws exception{ Myclassloader loader = new Myclassloader (); Class clazz = Loader.findclass ("E:\\myeclipse 10\\paragraph2\\bin\\loader\\hello.class"), Object obj = Clazz.newinstance (); System.out.println (obj);//system.out.println (Obj.getclass (). getClassLoader ()); Method m = Clazz.getmethod ("call", null); M.invoke (obj, null); System.out.println ("-------"); Hello h = new Hello (); System.out.println (h); H.call ();//Since the above twoobject is the same, can you convert it to one another? ※※ not, because the space is not the same. Class templates (bytecode objects) loaded by different ClassLoader will hang up here in different memory spaces Hello h2 = (hello) obj; System.out.println (H2);}}
Operation Result:
second, to make their own test tools Myjunit
(Case used for annotations and reflection)
Related instructions: 1) junit uses @test annotations, which we use @mytest annotations.
2) JUnit has been embedded in the MyEclipse, our own myjunit as long as we can run independently (without embedding), and so we do not have the convenience of myjunit in the parameter to receive the class name of the test class and method name, can only be keyboard output
Into the way received.
3) JUnit can implement a single method to invoke execution, because it cannot take advantage of myeclipse, so we traverse all the methods in the Myjunit program and decide whether to invoke execution of the method by judging whether the @mytest annotation is declared.
Mytest.java
Package Loader.myjunit;import Java.lang.annotation.elementtype;import Java.lang.annotation.retention;import Java.lang.annotation.retentionpolicy;import java.lang.annotation.Target; @Retention (retentionpolicy.runtime) @ Target (elementtype.method) public @interface MyTest {}
Mytestdemo.java
Package Loader.myjunit;public class Mytestdemo {public void aa () {System.out.println ("AAA");} @MyTestpublic void Bb () {System.out.println ("BBB"); @MyTestpublic void cc () {System.out.println ("CCC");}}
Myjunit.java
Package Loader.myjunit;import Java.lang.reflect.method;import Java.util.scanner;import Loader.myclassloader.myclassloader;public class Myjunit {public static void main (string[] args) throws Exception {System . OUT.PRINTLN ("Please enter the class to be tested:"); Scanner sc = new Scanner (system.in); String className = Sc.nextline ();//class clazz = Class.forName (className);//Must be a full class name (with package name)//object obj = Clazz.newinstance (); Myclassloader loader = new Myclassloader (); Class clazz = Loader.findclass (className); Object obj = Clazz.newinstance (); Method ms[] = Clazz.getdeclaredmethods (); for (Method M:ms) {Boolean boo = M.isannotationpresent (Mytest.class); if (boo) { M.invoke (obj, null);}}}
Operation Result:
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
java------JUnit, annotations, ClassLoader