简体   繁体   中英

How should I unit test Java that calls a MySQL stored procedure?

I'm writing a simple application that will read some records and insert them in a database. I've written a stored procedure that handles the insertion logic, and plan to test that separately. Now I'd like to write a good unit test for the portion of the logic that takes a business object and passes it to the stored procedure call.

I think what I want to do is pass a mock of the database connection, then assert that the call is made with expected parameter values:

Connection dbConnection = makeMockConnection();  // how?
MyObjectWriter writer = new MyObjectWriter(dbConnection);
writer.write(someSampleObject);
// somehow assert that dbConnection called
// `sp_saveMyObject` with param values x, y, and z

However, it seems like a lot of work dig around inside java.sql.Connection , understand how it works, then mock all the results. Is there a test library that does all this for me? Am I coming at this the wrong way?

You could create an in-memory HSSQL database with a mock stored procedure. The mock sproc would insert a row into a table to show that it ran and what it's parameters were. Run the code under test and then look in the db to see what happened.

You can use the Decorator design pattern for the connection mocking. You create a real Connection to the DB with the driver you use which is wrapped by your ConnectionImpl class that implements Connection interface and holds the real Connection as a member.
Every real call that you don't want to actually do, replace it with a mock code, and every call the stays call the real connection object's identical method (Delegate the call).
In this way you are coding as usual, only differ in the returned object from the method that creates the connection.
Now, in the mock object (your ConnectionImpl) you can add unit testing code that checks input, for example.

If you're not concerned with how MyObjectWriter works, just that it does, then I would be inclined to write an integration test and forget about a unit test.

You don't mention how you're testing the stored procedure, so forgive me, but what I would do is write tests around MyObjectWriter which invoke the actual stored-procedure on a database and then verify the database state afterwards. I would use an in-memory database, if possible, to keep test durations down.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM