-2

I want to write a test for a method that accesses a database such as following.

public class MyClass{
    public String getAddress(Int id){
        String query = "Select * from Address where id="+id;
        //some additional statements           
        resultSet = statement.executeQuery();
        return result.getString(ADDRESS);        
    }
}

How can I test this method? I am using Java.

3
  • @gnat I am new to java... I have just started learning junit and it seems that I have a lot of methods similar to ones I showed above. So I just wanted to know what I can use to test such a method because I was unable to do it using junit. Commented Nov 16, 2012 at 18:06
  • 2
    DBUnit is a JUnit extension that might help you. dbunit.org Commented Nov 16, 2012 at 18:16
  • 1
    I actually asked this today on SO - stackoverflow.com/questions/13413466/… .
    – Random42
    Commented Nov 16, 2012 at 19:49

2 Answers 2

1

You would probably be better served to skip the integration testing for most of these methods. Instead, you would want to look into mocks and stubs (Mockito is a well-regarded mocking framework for Java) and verifying that the method behaves in the proper way. Namely, building the expected SQL for the input (on a sidenote, you should be using parameterized queries, not just concatenating strings), passing it to the correct object, and returning the correct value from the mocked up row.

2

Remember that you aren't testing whether your database works.

If you are using a database from one of the top vendors (or even the second and third tiers) you can guarantee that they have tested that a SQL statement will read or write.

You probably want to test a number of things:

  • Did I get my connection properties right?
  • Do the columns returned by my SQL statement match my data structure?

etc

Some of these can be addressed by mocking frameworks (as described by another poster). Some of these might be setup as integration tests that run independently of unit tests. Some of these can be tested using an in-memory database.

I've used HSQLDB in the past to create an inmemory database, pre-populate with data and then run my unit tests. In memory databases are orders of magnitude quicker than a traditional database, you don't have to worry about setting up transactions to clean them up etc.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.