jaana
jaana

Reputation: 295

Unit testing Spring 3 database methods

I have abstract class that defines database methods, such as inserts and updates, and a concrete class that implements it. The database configurations (dataSource, DatabaseTarget etc) are defined as beans in context.xml-file.

The database with its methods work in Controller when I'm using Spring 3 anotations by

private AbsractClass a;

Constructor:

@Autowired
public Controller(AbstractClass a) {
    this.a =a;
}

...and a getter for a.

Calling database methods is done by

getA().insertValues();

But I would like to write Junit tests for my methods. Is there any example for this kind of situation? I have googled for hours.

Upvotes: 0

Views: 658

Answers (1)

goenning
goenning

Reputation: 6654

If you want to test your controller methods without touching the database (which is the correct way), create a new class that extends the AbsractClass and pass it as argument to your Controller class, example:

CustomerController controller= new CustomerController(new InMemoryCustomerDao());
//call your actions and assert, all calls to the database will hit the InMemoryDao.

Another way is to use a Mock Object if you don't want to create extra fake classes in your project or you need to assert that these arguments are being correctly called.

Upvotes: 1

Related Questions