Use junit Assert to determine whether the parameter is empty

This is a very useful junit practical skill. In daily development, we often need to evaluate parameters, such as a function.

 

[java]  view plain copy  
 
  1. public void test(String para1,Object para2)  
  2.     {  
  3.         if(para1!=null&¶2!=null){  
  4.             // handle business  
  5.         }else {  
  6.             //Throw an exception, or the program ends, etc.  
  7.         }  
  8.   
  9.     }  


If each parameter is separated to judge whether it is empty, there are too many if else judgments in the code, which is not clear and tidy. If it is judged together as above, it is impossible to know which parameter is empty. At this time, using junit's assertion judgment is a good choice.

 

[java]  view plain copy  
 
  1. public void test(Object para1,Object para2) throws Exception {  
  2.         Assert.notNull(para1, "para1 is required");  
  3.         Assert.notNull(para2, "para2 is required");  
  4.     }  

 

If the parameter is empty, an exception will be thrown upwards, and the exception will be caught at the top level, at the entry point of the program, or elsewhere. By printing the exception information, you can capture which parameter is empty and get a detailed description.

This can be extended a little. In development, we often need to ensure that the properties required by a class have been injected successfully. For example, the dao required for service execution has been injected successfully

We can make the current bean implement spring's InitializingBean interface,

  1. public class TestServiceImpl implements TestService, InitializingBean {  
  2.     /** testDAO */  
  3.     private testDAO testDAO;  
  4.   
  5.      
  6.     @Override  
  7.     public void afterPropertiesSet() throws Exception {  
  8.         Assert.notNull(testDAO, "testDAO instance is required");  
  9.     }  
  10. }  

Then rewrite the afterPropertiesSet() method, which will be executed after the bean is started, and ensure the correctness of the program by making a non-null judgment on the injected parameters.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325065313&siteId=291194637