"Error Code"
Public classuserdaotest{Privatesqlsessionfactory sqlsessionfactory; //This method executes prior to executing Testfinduserbyid ()@Before Public voidSetUp ()throwsException {//Create Sqlsessionfactory//mybatis configuration fileString resource= "Sqlmapconfig.xml"; //get configuration file streamInputStream inputstream=Resources.getresourceasstream (Resource); //creating a session factory, passing in MyBatis profile information sqlsessionfactory sqlsessionfactory=NewSqlsessionfactorybuilder (). Build (InputStream); } @Test Public voidTestfinduserbyid ()throwsException {//Create an Userdao objectUserdao Userdao =NewUserdaoimpl (sqlsessionfactory); //methods for calling UserdaoUser User =userdao.finduserbyid (4); System.out.println (User.tostring ()); }}
"Fix Code"
Public classuserdaotest{Privatesqlsessionfactory sqlsessionfactory; //This method executes prior to executing Testfinduserbyid ()@Before Public voidSetUp ()throwsException {//Create Sqlsessionfactory//mybatis configuration fileString resource= "Sqlmapconfig.xml"; //get configuration file streamInputStream inputstream=Resources.getresourceasstream (Resource); //creating a session factory, passing in MyBatis profile information sqlsessionfactory=NewSqlsessionfactorybuilder (). Build (InputStream); } @Test Public voidTestfinduserbyid ()throwsException {//Create an Userdao objectUserdao Userdao =NewUserdaoimpl (sqlsessionfactory); //methods for calling UserdaoUser User =userdao.finduserbyid (4); System.out.println (User.tostring ()); }}
"Cause analysis"
The @Before method executes before the @test method, copies the previous code directly, and defines the private sqlsessionfactory sqlsessionfactory in the class outside of the two methods;
Two methods are intended to be common, but they have copied the previous code, but ignore the @before will re-new an object,sqlsessionfactory sqlsessionfactory=new Sqlsessionfactorybuilder (). Build (InputStream); The final debug only found the error.
Write this article and remember not to make this mistake!
08_ a java.lang.NullPointException error