JAVA usage and unit testing points

Copyright: prohibited reproduced https://blog.csdn.net/qq_36505948/article/details/82797240
 
 

First, unit testing purposes?
      Unit testing is to write test code to detect a specific, clear, functional fine particles! Strictly speaking, unit tests only test for function points, excluding testing of business processes correctness. The company will now generally be tested business processes, which also requires testers need to understand the needs! Tester is not better ah ~ ~

      Currently developing unit is used Junit framework has been integrated in most java development environment, you can easily develop their own call!

Note: Unit testing is not only to ensure the correctness of the code, a good unit test reports, where the defects and problems, and the correct state but also a complete record, easy to fix behind the code, refactoring and improvements!


Second, what do unit testing?

In general, a unit testing includes the following aspects:

================================================== ============================================
1. interface functionality test : the correctness of the interface functions, namely to ensure that the interface can be properly called and valid data!

------------------> whether the call was successful

------------------> parameters are in line with expectations

================================================== ============================================
2. test local data structure : ensure the correctness of the data structure
------------------> whether the variable has an initial value or default value of the scene at a certain
---------- --------> variable has overflowed
====================================== ================================================== ======
3. boundary conditions testing:
------------------> variable no assignment (null)
------------ ------> variable is numeric or character
------------------> key border: maximum, minimum, infinity
--------- ---------> overflow boundary: boundary values outside the +/- 1
------------------> near the boundary: boundary values taken within value +/- 1
------------------> boundary string, citing border "variable character" of
-------------- ----> string set, the empty string
------------------> string length test application
------------ ------> blank collection
------------------> type and application boundaries of the target set
------------------> order collection
------------------> variable is the law, and test the limits of infinity infinitesimal limit
============================================== ================================================

4. All tests independent codes: a code to ensure that each, complete testing of all branches, including code coverage, exception processing path test
------------------> statement coverage : each statement to execute
------------------> coverage determination: each branch to execute
-------------- ----> condition coverage: each condition returns a Boolean
------------------> path coverage: each path coverage to

================================================== ============================================
The abnormal test modules, subsequent processing module test: if the current exception or closing the package formed abnormality digested affect the results!


Three, JAVA unit test JUNIT4

(1): business process generally in accordance with the desired effect of demand, finish the entire business process, including process previously developed
-----------------> whether to achieve the desired
- ---------------> is affecting the previous process
-----------------> the whole process is smooth
------ whether -----------> data in line with expectations

==============================================================================================

(2): Test Code:

  1. Global @BeforeClass only once, and was the first run
  2. @Before runs before running the test method
  3. @Test test methods
  4. @After allowed to run after the test method
  5. Global @AfterClass only once, and the last run
  6. Ignore this method @Ignore

JUNIT4 org.junit test is carried out as a framework, in the form of annotation method for identifying code to be tested!

note:

For each test, we should remain independent testing to ensure that test results are meaningful. In a program, often occur, when a finished testing method which parameters have been held down or persistent system. No doubt test the irrationality of test data or status of a lower result! To solve the problem, for such scenes, we must have the ability to test code to initialize and closeout. That is the significance of @Before and @After!

Similarly @AfterClass and BeforeClass i.e. to meet the test, those very bulky, but as long as one code block initialization!

(3): testing and assertions and commonly asserted:

   ---------->assertEquals:

  1. Assert.assertEquals ( "output prompt here", 5, the Result);
  2.  
  3. ===================================================================================================================
  4. Analysis: When "Output prompt here" for the personal mistakes you want error messages output; 5 refers to the value you would expect; result means that after you call your program to program output results
  5.  
  6. @Test(expected = NullPointerException.class)
  7. Resolution: Add comment at the time expected to ignore this exception
  8. @Test (timeout = 5000): timeout settings
  9. @Test (expected = XXXXException class.): Expectations abnormal, if the exception occurs if successful, otherwise the test fails
  10. @Ignore (): user above method, the annotated method will be successful to be ignored
  11. ===================================================================================================================
  12.  
  13. fail( "Not yet implemented")
  14. Analysis: on the approach, if I execute successfully, I reported to fail out. That is not supposed to be here to perform, but it happens executed, indicating a problem with the program
  15. ===================================================================================================================
  16. Assert.assertTrue( "msg",boolean)与Assert.assertFalse("msg",boolean)
  17. Analysis: If as expected is true then the success, or failure output msg; if as expected as false if successful, otherwise fail and output

  ----------> assertNull("msg",boolean)与assertNotNull("msg",boolean)

解析:assertNull与assertNotNull可以验证所测试的对象是否为空或不为空,如果和预期的相同则测试成功,否则测试失败!

======================================== main common method ======= =====================================

List assertion:
--------------> assertTrue (the Message String, boolean for condition Condition) == to true requirements for condition Condition
--------------> assertFalse (the Message String , boolean condition) == required to false for condition Condition
--------------> the assertEquals (String Message, expected XXX, XXX Actual) expected required can be equal to a desired value Actual
------- -------> assertArrayEquals (String message, XXX [] expecteds, XXX [] actuals) in claim expected.equalsArray (Actual)
--------------> assertNotNull (String Message, Object object) in claim Object! = null
--------------> assertNull (Message String, Object object) == null claim Object
-------------- > assertSame (String message, Object expected , Object actual) requirements expected == actual
-------------->assertNotSame(String message, Object unexpected,Object actual) 要求expected != actual
-------------->assertThat(String reason, T actual, Matcher matcher)  要求matcher.matches(actual) == true

--------------> fail (String message) requires the implementation of the target structure is bound to fail, the same code is not up to the requirements, that is, this method does not return success after the program is running, if successful return of the error

(4): Runner specified?

The test unit, each class is due JUNIT4 frame Runner runner performed. In general, in the runner when not specified, the default selection (TestClassRunner) operation is performed by the system. All methods include the class are responsible for the operation of call and execution. When we need to specify when the selection comment @Run Wirth (xxxxxx) by class level, usually choose different actuators, depending on the type, can improve the efficiency can also be applied to a particular scene!

(5): parametric test?

  1.   @RunWith(Parameterized. class )
  2.   public   class  TestParam {
  3.  
  4.        Private    static the Calculator Calculator =    new new the Calculator ();  // class to be tested
  5.        private   int  param; 
  6.        private   int  result;
  7.  
  8. @Parameters
  9. public   static  Collection data(){
  10.  
  11.     return  Arrays.asList(new  Object[][] {{ 11 ,  17 } , { xx1 ,  xx} } );
  12.  
  13.  
  14. // constructor have parameters, initialization parameters achieved when the instance of
  15. public  TestParamint  param,  int  result){
  16.   this .param  =  param;
  17.   this .result  =  result;
  18.  
  19. @Test
  20. public  void  TestResult(){
  21.    calculator.square(param);
  22.    assertEquals(result, calculator.getResult()); 
  23.  

Commentary: target parameters of the test is to complete the same types of disposable testing, the same type of data in a certain order to the incoming batch testing method, and concluded that the essence of a batch operation, but for convenience! we have conducted tests package. We only provide testing methods and be in a certain order can be set.

---------> for class annotation: @RunWith (Parameterized.class), in order to specify a test class runner ParameterizedRunner

---------> parameter settings: The expected results and the test results, each set is in the form of a storage array to form a two-dimensional array, and returns the transformed annotated list.

---------> Parameter Initialization: To test the setting parameters of the parameter, and in accordance with the "parameter set" in this order using the constructor initializes the assignment!

---------> Test calls: calls to write a test method, a method to pass parameters to class to be tested and returns the data

Note: parametric tests need to create a separate test class for testing. And define two variables for accepting test results and expectations. Data is stored in a two-dimensional array, a set of two. Data is then initialized by the constructor. The method of construction into the reference sequence to the sequence and two-dimensional array of data stored in each group of China consistency.


(6): Packaging test?

  1. @RunWith(Suite. class )
  2. @Suite.SuiteClasses( {CalculatorTest. class ,SquareTest. class } )
  3. public   class  AllCalculatorTests  {
  4. //to do something;
  5. ==========================================================================================================================
  6. Analysis: There will need to execute the program together with the package, and then perform
  7. Runner:. Suite  class

Analysis: We need to package the test class test together as a parameter passed to the annotation. Then directly run the code, test class here can be directly set to null, just add annotations will be OK;

 

Guess you like

Origin www.cnblogs.com/yangf428/p/11088480.html