In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article introduces the relevant knowledge of "what is the method of Hibernate unit testing". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
Many methods have been used to transfer data between the database and the object code. From hand-coded SQL to JDO, and then to EJB, I've never found a favorite method. This dissatisfaction has intensified since the adoption of test-driven development (TDD) as a guiding principle.
The obstacles to unit testing should be as few as possible. In a relational database, the scope of obstacles is externally dependent (is the database running? To the speed of keeping the relational model and the object model synchronized For these reasons, it is important to keep the database access code separate from the core object model and do as much testing as possible without involving the real database.
Usually this leads us to one of the following two modes. * is to specify the data that accesses all domain objects and the relationship between the data and individual classes or interfaces. This is a typical data store object that can retrieve, edit, delete, and add domain entities. This is the easiest to simulate in unit testing, but tends to treat domain model objects as pure data objects without any relational behavior. It is ideal to access child records directly from the parent object, rather than treating the parent object as a third-party class to determine the child record.
Other methods have brought domain objects of the access interface into the data mapping layer (a data mapping mode of la Martin Fowler). This has the advantage of promoting the object relationship in the domain model, where the object relational interface only needs to be expressed once. Classes that use the domain model do not support the persistence mechanism because it itself is internalized into the domain model. This allows the code to focus on the business problems it is trying to solve, with little attention to the object-relational mapping mechanism.
My current project involves processing large amounts of baseball statistics and using them for simulation. Because the data is already in the relational database, it is an opportunity for me to develop an Hibernate object-relational mapping system. I was impressed with Hibernate, but one of the problems I encountered was trying to insert an indirect layer when using Hibernate for data mapping for unit testing. This additional layer is very fragile and very difficult to write. The actual deployment version simply passes a Hibernate-specific implementation. To make matters worse, the simulation version is more complex than the real "production" version, simply because there is no basic object storage and mapping with Hibernate in the simulation version.
I also use a lot of complex Hibernate queries and want to unit test important parts of the application. However, it is not a good idea to test the active database because it almost always creates maintenance problems. In addition, because the tests are independent of each other, using the same primary key in the test context data means that code must be created before each test to clean up the database, which becomes a real problem when a large number of relationships are involved.
By using the powerful schema generation tools of HSQLDB and Hibernate, you can unit test the mapping layer of an application and find countless bug in object queries, which is not possible in previous manual testing. Using the following technical overview, the entire application can be tested during the development process without damage within the test effective area.
Set up HSQLDB
Previously used HSQLDB version 1.7.3.0. To use the in-memory version of the database, you need to activate the static loader for org.hsqldb.JDBCDriver. When you get a JDBC connection, you can use JDBC url such as jdbc:hspldb:mem:yourdb, where 'yourdb' is the name of the in-memory database you want to use.
Because I use Hibernate (3. 0 beta 4), I have little contact with the actual active JDBC object. Instead, I can get Hibernate to do a lot of onerous tasks, including automatically creating database schemas from Hibernate mapping files. Because Hibernate creates its own proprietary connection pool, it automatically loads the HSQLDB JDBC driver based on the configuration code in the TestSchema class. Here is the static initialization program for this class.
Public class TestSchema {static {Configuration config = new Configuration (). SetProperty ("hibernate.dialect", "org.hibernate.dialect.HSQLDialect"). SetProperty ("hibernate.connection.driver_class", "org.hsqldb.jdbcDriver"). SetProperty ("hibernate.connection.url", "jdbc:hsqldb:mem:baseball"). SetProperty ("hibernate.connection.username", "sa"). SetProperty ("hibernate.connection.passWord", "). SetProperty (" hibernate.connection.pool_size ") SetProperty ("hibernate.connection.autocommit", "true"). SetProperty ("hibernate.cache.provider_class", "org.hibernate.cache.HashtableCacheProvider"). SetProperty ("hibernate.hbm2ddl.auto", "create-drop"). SetProperty ("hibernate.show_sql", "true") .addClass (Player.class) .addClass (BattingStint.class) .addClass (FieldingStint.class) .addClass (PitchingStint.class) HibernateUtil.setSessionFactory (config.buildSessionFactory ());}
Hibernate provides many different ways to configure the framework, including programmatic configuration. The above code sets up connection pooling. Note that the in-memory database using HSQLDB requires the user name 'sa'. Also be sure to specify a space as the password. To start the automatic mode generation function of Hibernate, set the hibernate.hbm2ddl.auto property to 'creat-drop'.
My actual test project was to deal with large amounts of baseball data, so I added four mapped classes (Player, PintchingStint, BattingSint, and FieldStint). * create a session factory for Hibernate and insert it into the HibernateUtil class, which provides only one access method for the entire application of the Hibernate session. The code for HibernateUtil is as follows:
Import org.hibernate.*;import org.hibernate.cfg.Configuration;public class HibernateUtil {private static SessionFactory factory;public static synchronized Session getSession () {if (factory = = null) {factory = new Configuration () .buildSessionFactory ();} return factory.openSession ();} public static void setSessionFactory (SessionFactory factory) {HibernateUtil.factory = factory;}}
Because all code (production code that has been unit tested) gets the Hibernate session from HibernateUtil, it can be configured in the same location. Accessing the TestSchema class for unit testing of the * bits of the code will activate the static initialization program, which installs Hibernate and inserts the test SessionFactory into the HibernateUtil. For production code, the standard hibernate.cfg.XML configuration mechanism can be used to initialize SessionFactory. So what are the external characteristics in unit testing? The following test code snippet is used to check the logic to determine where the player is in a baseball league game:
Public void testGetEligiblePositions () throws Exception {Player player = new Player ("playerId"); TestSchema.addPlayer (player); FieldingStint stint1 = new FieldingStint ("playerId", 2004, "SEA", Position.CATCHER); stint1.setGames (20); TestSchema.addFieldingStint (stint1); Set
* create a new Player instance and add it to the TestSchema through the addPlayer () method. You must complete this step first because there is a foreign key relationship between the FidldStint class and the Player class. If you do not add the instance first, a foreign key constraint violation will occur when you try to add FieldingStint. Once the test context is in place, you can test the getEligiblePositions () method to retrieve the correction data. Here is the code for the addPlayer () method in TsetSchema. You will notice using Hibernate instead of bare-metal JDBC code:
Public static void addPlayer (Player player) {if (player.getPlayerId () = = null) {throw new IllegalArgumentException ("No primary key specified");} Session session = HibernateUtil.getSession (); Transaction transaction = session.beginTransaction (); try {session.save (player, player.getPlayerId ()); transaction.commit ();}
The most important thing in unit testing is to keep the test instance independent. Because this method still involves a database, you need a way to clean up the database before each test instance. There are four tables in my database schema, so I wrote the reset () method on TestSchemaz, which deletes all rows from the table that uses JDBC. Note that because HSQLDB recognizes foreign keys, the order in which tables are deleted is important. Here is the code:
Public static void reset () throws SchemaException {Session session = HibernateUtil.getSession (); try {Connection connection = session.connection (); try {Statement statement = connection.createStatement (); try {statement.executeUpdate ("delete from Batting"); statement.executeUpdate ("delete from Fielding"); statement.executeUpdate ("delete from Pitching"); statement.executeUpdate ("delete from Player"); connection.commit ();} finally {statement.close ();}} catch (HibernateException e) {connection.rollback (); throw new SchemaException (e) } catch (SQLException e) {connection.rollback (); throw new SchemaException (e);}} catch (SQLException e) {throw new SchemaException (e);} finally {session.close ();}}
When it is determined that a large number of deletions are performed in Hibernate 3.0, it should be possible to remove the direct JDBC bit from the application. At this point, you must obtain the database connection and submit the SQL directly to the database. In order to free resources, it is sufficient to just close the session while ensuring that the connection is not closed. Out of the habit of writing a lot of JCBC code by hand for development, * versions have closed JDBC connections. Because the connection pool created by configuring Hibernate has only one link, it completely destroys the test after *. We must pay attention to this situation! Since you cannot determine the state of the database while the test class is running (imagine running all the test instances), you should include database cleanup in the setUp () method, as follows:
That's all for public void setUp () throws Exception {TestSchema.reset ();} "what is the method of Hibernate unit testing?" Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.