I have used easymock for creating a java.sql.Connection mock object(con). My doubt is
Should i use con=null for cleanup or
con.close() for cleanup ?
In my opinion it should be the first one but still wanted to clear my doubts.
It is a mock object so it will not be creating actual connection to the database. So, the first one should suffice in my opinion. If you call conn.close(), you will have to mock it anyways.
Related
When trying to use Mockito with Spring, by creating the Mock object via a bean declaration...
<bean id="accountMapper" class="org.mockito.Mockito" factory-method="mock">
<constructor-arg value="org.example.persistence.mybatis.mappers.AccountMapper" />
</bean>
...I found some strange behavior when calling Mockito.when multiple times without reseting the Mock object, for example:
Mockito.when(this.accountMapper.createBadGrammarException()).thenThrow(new BadSqlGrammarException("Bla", null, new SQLException()));
As soon as this code (the "Mockito.when") is called multiple time during the test (on the same mock), the tests fails with an error (BadSqlGrammerException even if this exception was what was actually expected - I do get a failure if I don't throw the exception, and throwing it manually works fine). Is this expected behavior? Mockito seems to suggest creating a new mock every time, which would mean creating the DAO for each method...?
What exactly happens when I call the Mockito.when method two times? How should the mock react? Replace the behavior? Ignore it? Unfortunately most searches only yield results for how to return different results for multiple calls to the method itself, but not what is to be expected for multiple calls to Mockito.when...
I'm simply trying to understand Mockito and best practices here, because going with something just because it SEEMS to works seems to be a bad idea...
One of the problems with Mockito.when is that the argument you pass to it is the expression that you're trying to stub. So when you use Mockito.when twice for the same method call, the second time you use it, you'll actually get the behaviour that you stubbed the first time.
I actually recommend NOT using Mockito.when. There are many traps that you can fall into when you use it - quite a few cases when you need some other syntax instead. The "safer" alternative syntax is the "do" family of Mockito methods.
doReturn(value).when(mock).method(arguments ...);
doThrow(exception).when(mock).method(arguments ...);
doAnswer(answer).when(mock).method(arguments ...);
So in your case, you want
doThrow(new BadSqlGrammarException(??, ??, ??)).when(accountMapper).createBadGrammarException();
If you are starting out with Mockito, then I recommend that you learn to use the "do" family. They're the only way to mock void methods, and the Mockito documentation specifically mentions that. But they can be used whenever Mockito.when can be used. So if you use the "do" family, you'll end up with more consistency in your tests, and less of a learning curve.
For more information about the cases when you must use the "do" family, see my answer on Forming Mockito "grammars"
The simple answer is:
when you write Mockito.when(object.fooMethod()).then() then fooMethod() is actually called.
Another point is that we can't observe it first time, because it called on mocked object. But when we write when for the second time then we have some behavior for fooMethod() (we set it previously, in your case it Exception).
To check this better you can spy object:
Bar spyBar = Mockito.spy(Bar.class)
when(spyBar.fooMethod()).then()...
and fooMethod() will be actually called.
I'm using Mockito in order to do some mocks/testing. My scenario is simple : I have a class mocked using mock() and I'm invoking this class (indirectly) for a large number of times (i.e. ~100k)
Mockito seems to hold some data for every invocation, and so I run out of memory at a certain point.
I'd like to tell mockito not to hold any data (I don't intend to call verify(), etc, I just don't care, for this specific tests, what reaches to that mock). I don't want to create new mocks with every invocation.
You can use Mockito.reset(mock), just be aware that after you call it, your mock will forget all stubbing as well as all interactions, so you would need to set it up again. Mockito's documentation on the method has these usage instructions:
List mock = mock(List.class);
when(mock.size()).thenReturn(10);
mock.add(1);
reset(mock);
//at this point the mock forgot any interactions & stubbing
They do also discourage use of this method, like the comments on your question do. Usually it means you could refactor your test to be more focused:
Instead of reset() please consider writing simple, small and focused test methods over lengthy, over-specified tests. First potential code smell is reset() in the middle of the test method. This probably means you're testing too much. Follow the whisper of your test methods: "Please keep us small & focused on single behavior". There are several threads about it on mockito mailing list.
I want to test my class MyTypeDAO implemented with Hibernate 4.1 using JUnit 4.9. I have the following question:
In my DAO, I have a findById method that retrieve an instance of my type by its ID. How to test this method?
What I've done:
I create an instance of my type.
Then, I need to persist this instance, but how? Can I rely on my saveMyType method? I don't think so, since I'm in the test case and this method is not tested.
Then, I need to call the findById method with the ID of the instance created in step 1.
Finally, I check that the instance created in step 1 equals the one I get in step 3.
Any idea? What are the best practices?
I have the same questions for the save method, since after running it, I need to retrieve the save instance. Here also, I don't think I can rely on my findById method since it's not already tested.
Thanks
One possible way is:
Create a in memory db for testing, load contents of this db from a predefined sql script andthen test your DAO classes against this database.
Everytime you start tests, database will be created from scratch using the sql script and you will know which id should return a result and which one should not.
See [DbUnit][1] (from satoshi's comment)
I don't think you have much choice to achieve this. It's not a good practice to have orthognal tests (tests that test 2 things or are dependent). Nevertheless, you should really consider this exception valid and fast. You are right : persisting an object and retrieving it is a good idea to test this dao layer.
Other options include having a record that you are sure about in the database and testing the retrieval (findById) on it. And the a second test to persist an object and removing it the teardown method.
But really, it would be simpler to test loading and saving together and it makes much sense.
Currently what i am doing for transaction management is:
Connection connection = getConnection();
connection.setAutoCommit(false);
updateTableX ( connection, ... );
updateTableY ( connection, ... );
connection.commit();
closeConnection();
I would like to know, if it is possible to avoid closing the connection in my 'updateTableX' method. Because if someone accidentally closes the connection then my updateTableY will not be having the connection and it will throw the exception.
Just discipline. In general, methods shouldn't try to take responsibility for closing things passed into them as parameters - with the exception of situations where you create a new object to wrap an existing one.
The way to avoid closing the connection in updateTableX is just to make sure you don't put a call to close() into the code. This is no different than any other bug really. How do you stop updateTableX from arbitrarily updating a different table, or throwing an exception, or doing anything else it's not meant to? Code reviews, unit tests, integration tests, manual testing etc...
I mean you could write a Connection implementation which wraps another connection and proxies all the methods through except close() but it sounds like a waste of time - if you don't trust the developers involved not to close the connection, do you trust them to get the rest of the code right?
Like Jon said, if you really want to forbit to call close() you could write a decorator implementation that forwards to your "real" Connection object. I don't post a code example because the Connection interface is too big. With modern IDEs however it is no problem to generate the code.
Recipe (presuming you're using Eclipse):
Create a class that implements Connection, but do not implement the methods
Create a field private Connection delegate;
Select the field name -> Source (Menu) -> "Generate Constructor using fields" -> make sure the field is selected and press ok
Select the field name -> Source (Menu) -> "Generate Delegate Methods..." -> check every method on you field
Change the implementation of the close() method to throw an UnsupportedOperationException
However like Jon said, I would really think about doing something like that. And maybe you just use a Object-Relational-Mapper (e.g. Hiberate) to encapsulate all of your Database access logic. An additional very helpful framework in this area is Spring, especially if you do not want to care about Connection and DataSource handling.
(I am unfamiliar with Java specifically)
Assuming you have some sort of database managing object, you could have it make sure it is connected before it attempts any operations.
You could try to restrict access to closing the connection but how would you decide if it should be closed, or if it's "accidental" (however you define that)?
I don't think what you are asking is possible.
You can technically make a copy of your connection object, but then what happens if the client programmer doesn't close the connection?
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?
Thanks
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...
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.
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().
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) {
getJdbcTemplate().update(
"update mytable set name = ? where id = ?",
new Object[] {name, new Integer(id)});
}
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.
#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.