How to mock classes instantiated as local variables

I'm writing tests for a business method that invokes some DAO classes to perform operations over a database.

This method, firstly retrieves a JDBC connection from a DataSource object, The same connection is passed to all DAO instances, so I can use it to control the transaction. So, if everything works properly, I must invoke commit() over the connection object.

I would like to test if the commit() is invoked, so I've thought to create an expectation (I'm using JMock) that checks that. But since the Connection class isn't a direct neighbour from my Business class, I don't know how to do this.

Someone knows how to overcome this? There is some JMock facility for this, or some alternative design that allows to overcome this?


Asked by: Julian933 | Posted: 23-01-2022

Answer 1

You need to mock DataSource and Connection so that your mock DataSource returns your mock Connection. And yes, this kind of thing ends up becoming a real pain...

Answered by: Grace742 | Posted: 24-02-2022

Answer 2

It's hard for me to tell from your description exactly how your classes are composed, but the DataSource should be injected into your DAO class, either thru it's constructor or a setDataSource() method.

This would allow you to test the DAO in isolation, and allow you to construct the mock DataSource in your unit test and pass it to the DAO being tested.

Answered by: Oliver576 | Posted: 24-02-2022

Answer 3

Refactor so that the Connection is injected into the Dao and the Dao injected into the business class. You can then mock the Dao and / or the Connection. You can easily write your own mock that extends the Connection and overrides connect() to set a boolean that you later retrieve via a method that write such as wasConnectCalled().

Answered by: Briony611 | Posted: 24-02-2022

Answer 4

I would definitely recommend that you use spring-jdbc instead of trying to write this kind of code yourself. This will make sure that the connection, statement and resultset are closed correctly. Spring also has excellent transaction management so you simply don't have to worry about this.

For example take a look at this typical update statement using spring-jdbc:

public void updateName(int id, String name) {
            "update mytable set name = ? where id = ?", 
            new Object[] {name, new Integer(id)});

Answered by: Audrey717 | Posted: 24-02-2022

Answer 5

Make the bussines class retrieve the local variables from a global/static object factory. That way you could put the factory in test mode and make it return mock objects instead of real ones.

That should make it.

Answered by: Emma536 | Posted: 24-02-2022

Answer 6

@Paul seconded. And once you've split management of the connection out, you can write the rest of the behaviour in a callback that you pass into the thing that owns the connection -- like a UnitOfWork. The connection owner handles the transaction around, and passes the connection to, the UnitOfWork. Transactions in one place -- easy to test, UnitOfWork in another place, tested with a mock connection.

Answered by: Julian536 | Posted: 24-02-2022

Similar questions

java - When calling a method from another class, do variables in that method have to be instantiated in the class calling the method?

Another similar question: When calling a method (from separate class) that returns a value which is derived from another class (from within the separate class). Do we need to instantiate the variables of derived class in that calling method?

It tells me that the variables at not instantiated Java

Hey guys I am very new to programming I was practicing with a exercise question and I was doing the exercise I tried compiling the code that I already had typed, but it came back with year has not been initialized and the same error goes with investment. here is my code that I have right now. What am I doing wrong? by the way the variable future = investment * (1 + interest_rate)^year year is a exponent. im...

java - Static methods & variables in instantiated classes

Say I have a class Person, which has a method doSomething(). I create a static ArrayList<Person> people, and a method doSomethingToAllPeople() which calls doSomething() for each Person in people. Should I put people and doSomethingToAllPeople() in the Person class or in a different P...

java - Should static variables be used in a class that only gets instantiated once

I am creating a game in Java. I have this Director class which sets up my game thread and mostly deals with how the game operates. The class never should and is not instantiated more than once. Should the variables inside the class be static variables or not? I'm curious about what the java coding convention(if not every other object-orientated language) would be for something like this. Thanks!

java - load the data of an object by method after creating, or get a instantiated object with loaded data direct?

In a webapp, i have a data-model (let's call it Item). The data of this Item is filled by two methods. The first method is a XML parser (data import), the second reads the Data from a Database (while parsing the website). I see two possible ways to implement this class: first way: public class Item() { public void parseFromXML(String xml) { //xml parse code } ...

java - Define constraints on the context in which as class is instantiated

I wonder if there's a way to define a class in such a way that instances of it will never be members of another class (only local variables), or the other way round - only members but never local. Is there any way in which a class can dictate the scope of it's prospective instances?

user interface - How to load already instantiated JComboBox with data in Java?

I have a Swings GUI which contains a JComboBox and I want to load data into it from the database. I have retrieved the data from the database in a String Array. Now how can I populate this String array into the JComboBox EDITED==================================================================== In actual, the JComboBox is already instantiated when the java GUI is shown to the user. So I can't pass t...

user interface - How to add objects to a already instantiated JList in Java?

I want to add objects to a JList which has already been instantiated by the Netbeans genrated code. I can't pass my own list model in the JList constructor as I can't modify the Netbeans generated code. How can I add object to that JList.

In Java are the object instances for field constants that represent an enum type instantiated only when first accessed?

How are enums handled when it comes to the heap, memory, and when an enum type instance is created? If I've got an enum with fifty field constants, then do I have fifty objects on the heap representing that enum type (when accessed), and are there performance concerns?

java - Spring: How to assure that a class is only instantiated by spring and not by keyword new

Is it possible to assure that only spring can instantiate a class, and not by the keyword new at compile time? (To avoid instantiating by accident) Thank you!

java - Can a Static Nested Class be Instantiated Multiple Times?

Given what I know of every other type of static feature of programming––I would think the answer is 'no'. However, seeing statements like OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass(); makes me wonder.

java - How to make ActionBean be instantiated immediately but not after I call one of handlers?

I'm trying to make something simple with Stripes. I've read and heard a lot about easiness of using this framework and about steep learning curve (i.e. learning is quite fast and productive). But till this moment I can't even create the simplest HelloWorld with Stripes. All examples I've found demonstrate functionality like: "click on the link --> see the result". When we click on the link special handler ...

In Java what happens when an object fails to be instantiated?

I come from a c++ background and I find myself constantly doing this in java: SomeClass sc=new SomeClass(); if(null!=sc) { sc.doSomething(); } What I want to know is what will be in the variable sc if the constructor fails for some reason (like maybe not enough memory). I can' t find a straight answer, and I am worried that I am just wasting my time because maybe if the new operator ...

java - when is a spring bean instantiated

ApplicationContext ctx = new ClassPathXmlApplicationContext( "com/springinaction/springidol/spring-idol.xml"); Performer performer = (Performer) ctx.getBean("duke"); performer.perform(); In the above, when are the beans instantiated, when the ApplicationContext is created or when the getBean() is called?

Still can't find your answer? Check out these amazing Java communities for help...

Java Reddit Community | Java Help Reddit Community | Java Community | Java Discord | Java Programmers (Facebook) | Java developers (Facebook)