java


Unit test DB calls


I have a class with static functions performing DB operations such as save, retrieve and delete.
My DB class:
public final class DbUtils {
static {
DB_USER = //get from secure server
DB_PASSWORD = //get from secure server
}
private static Connection establishConnection() {
}
private static void closeConnection(Connection connection) {
}
public static boolean saveObject(final Object graph, final Object map) {
Connection connection = establishConnection();
try {
byte[] bgraph = ConvertToByte(graph);
byte[] bmap = ConvertToByte(map);
statement = connection.prepareStatement("INSERT IGNORE INTO " + TABLE_NAME + " VALUES (?,?)");
statement.setObject(1, graph);
statement.setObject(2, map);
statement.executeUpdate();
//Close statement within try catch
} catch(Exception e) { // also other exception
//catch to catch all type of exception
}
closeConnection(connection);
return true;
}
public static Map<String, Object> retrieveObject(final String key) {
Connection connection = establishConnection();
//read byte and convert to object
closeConnection(connection);
return map;
}
public static boolean deleteObject(final String key) {
Connection connection = establishConnection();
//delete all object except object with key
closeConnection(connection);
return (affectedRow >= 1);
}
}
I wrote a unit test to test it like this:
#RunWith(PowerMockRunner.class)
#PrepareForTest(DbUtils.class)
#SuppressStaticInitializationFor("DbUtils")
public class DbUtilsTest {
#Mock
Connection connection;
#Mock
ModuleDependencyGraph dependencyGraph;
#Mock
private Map<String , String> moduleSDF;
#Test
public void testSaveObject() throws Exception {
PowerMockito.spy(DbUtils.class);
PowerMockito.doReturn(connection).when(DbUtils.class, "establishConnection");
Assert.assertTrue(DbUtils.saveObject(dependencyGraph, moduleSDF));
}
}
When i try to run this unit test i get a null pointer error at the statement = connection.prepareStatement line which is to be expected i think since I'm not mocking the connection properly. How do I mock the connection properly? Also is the way I have written the saveObject test correct? I am new to unit-testing so I don't know the best-practices and how to cover all cases.
#Mock
Statement statement;
doReturn(statement).when(connection).prepareStatement(anyString());
doNothing().when(statement).setObject(any(), any());
doNothing().when(statement).executeUpdate();
This is using just Mockito. You can as well use PowerMockito. It should work none the less.

Related Links

Log setting for AXIS2 server
JSON to Java parser-Android
How to deserialize a json data using GSON?
Required Integer parameter 'id' is not present
Array Index Out of Bounds Exception while solving N Queens
Is it possible use hystrix circuit braker with zuul?
How to remove an event handler?
Spring MVC How to sort BindingResult form with hibernate validator errors
Descriptor with default root element was not found in the project jaxb unmarshall
Android OkHttp3 and Spring.io Post Multipart Data
Connection to MongoDB with Java
SQL “SCRIPT” command to backup h2 database
Empty table generation from DynamicJasper
Fixing my loop and needing assistance on Input Checker, Java
ApplicationContext with global variable lost after back pressed
How to parse raw activity data received from Mi Band

Categories

HOME
pdf
hive
minimum-spanning-tree
ngrx
view
hp-exstream
office365api
enterprise-library-5
convolution
ios-charts
directx
elasticsearch-hadoop
vifm
dax
qt-creator
leiningen
telephony
progressive-web-apps
reactive-cocoa
connection-string
openedx
swiftlint
xlsxwriter
java-3d
mps
language-agnostic
fish
uninstall
rst2pdf
webkitspeechrecognition
yadcf
semantic-versioning
data-manipulation
fog
caret
commit
mpmediaquery
bytecode-manipulation
lto
hilbert-curve
cookiecutter-django
broadcastreceiver
sfdc
g-code
glew
eigenvalue
heightmap
gpx
eclipse-gef
rails-routing
domain-model
mu
idisposable
diagnostics
media-player
imanage
firmata
spring-android
ado.net-entity-data-model
transmitfile
merge-conflict-resolution
impresspages
websitepanel
skype4py
master-slave
dlna
ptrace
uid
lib.web.mvc
cyclomatic-complexity
qdialog
mutation-observers
fluid-dynamics
lustre
umbraco6
directoryservices
npapi
block-device
coldbox
gui-test-framework
seaside
android-2.2-froyo
transcoding
oracle-warehouse-builder
message-driven-bean
intentservice
prettify
xsockets.net
jmapviewer
opcache
file-locking
html-editor
http-unit
bitsharp
trusted
dbproviderfactories
parametric-equations
bubble-chart
gnu-prolog
cinema-4d
xfbml
datareader
gin
zend-decorators
sector

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App