mocking database connection by using mockito - junit

public List<Prisma> getProductCharacteristics(ResultSetLoadHandler<Prisma> rsLoadHandler, SqlSession sqlSession) throws Exception {
List<Prisma> ptos = null;
try {
sqlSession.select("Product.getProductInformation", params, rsLoadHandler);
ptos = rsLoadHandler.getResults();
} catch (Exception e) {
throw e;
}
return ptos;
}
I am trying to mock the select method
Mockito.doAnswer(new Answer() {
#Override
public Object answer(InvocationOnMock invocation) throws Throwable {
return rsLoadHandler;
}
}).when(sqlSession).select(rsLoadHandler, sqlSession);
but not able to mock sqlSession.select(String statement, Object parameter, ResultHandler handler); in mockito framework.
Getting this issue:
org.springframework.jdbc.CannotGetJdbcConnectionException: Could not
get JDBC Connection; nested exception is
org.apache.commons.dbcp.SQLNestedException: Cannot create
PoolableConnectionFactory (ORA-28000: the account is locked )
I am using ibatis database, I need to mock the db calls
I should not hit the database and return the list size to be greater than zero.

Related

Executed rollbackon connection

i am using JDBC to connect my MySQL database. I am trying to delete data from 2 tables (tasks and tasks_users(join table)). Look at my code:
#Override
public int deleteById(Long id) throws SQLException {
deleteByIdFromJoinTable(id);
int updated_rows;
sessionManager.beginSession();
try(Connection connection = sessionManager.getCurrentSession();
PreparedStatement statement = connection.prepareStatement(SQL_QUERIES.DELETE_TASK_BY_ID.QUERY)) {
statement.setLong(1, id);
updated_rows = statement.executeUpdate();
sessionManager.commitSession();
}catch (SQLException exception){
log.error(exception.getMessage(), exception);
sessionManager.rollbackSession();
throw exception;
}
return updated_rows;
}
public void deleteByIdFromJoinTable(Long id) throws SQLException {
sessionManager.beginSession();
try(Connection connection = sessionManager.getCurrentSession();
PreparedStatement statement = connection.prepareStatement(SQL_QUERIES.DELETE_TASK_FROM_TASKS_USERS.QUERY)) {
statement.setLong(1, id);
statement.executeUpdate();
sessionManager.commitSession();
}catch (SQLException exception){
log.error(exception.getMessage(), exception);
sessionManager.rollbackSession();
throw exception;
}
}
enum SQL_QUERIES {
DELETE_TASK_BY_ID("DELETE FROM tasks WHERE id=(?)"),
DELETE_TASK_FROM_TASKS_USERS("DELETE FROM tasks_users WHERE task_id=(?)");
final String QUERY;
SQL_QUERIES(String QUERY) {
this.QUERY = QUERY;
}
}
}
But when i call deleteById(), i get exception like:
13:58:03.079 [http-nio-8080-exec-9] DEBUG com.zaxxer.hikari.pool.ProxyConnection - restServiceDbPool - Executed rollback on connection com.mysql.cj.jdbc.ConnectionImpl#68421fee due to dirty commit state on close()
Connection to database works well, method, where i get all tasks returns them without problems.
What's problem is here, i will be very grateful for help?

Asp.Net Wep Api - Return Internal Server Error with exception details

Is there a way I can return internal server error with the exception details?
For example if I have something like the following:
[HttpPost]
public IHttpActionResult test(MyDto dto)
{
using (var transaction = _unitOfWork.BeginTransaction())
{
try
{
//do some stuff
transaction.Commit();
return Ok();
}
catch (Exception ex)
{
transaction.Rollback();
return InternalServerError(new Exception(ex.Message));
}
}
}
Which give me the following. but as you can see there is no inner exception details to provide any meaningful information.
{
"message": "An error has occurred.",
"exceptionMessage": "An error occurred while updating the entries. See the
inner exception for details.",
"exceptionType": "System.Exception",
"stackTrace": null
}
Basically I would like some more info regarding the exception as an when it occurs so that I can troubleshoot?
The easiest way to expose the exception details is to set the configuration property IncludeErrorDetailPolicy = Always in your HttpConfiguration or. Web.conf.
https://learn.microsoft.com/en-us/aspnet/web-api/overview/advanced/configuring-aspnet-web-api
After that, you can throw your execption and asp.net creates the InternalServerError-Response.
Another way is to create your own error object and retuns it with the information.
But you should be careful with providing to much information about your internal server information for security reasones.
public static void Register(HttpConfiguration config)
{
Logger.Info("WebApiConfig: Register: Start");
config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
// ...
}
[HttpPost]
public IHttpActionResult test(MyDto dto)
{
using (var transaction = _unitOfWork.BeginTransaction())
{
try
{
//do some stuff
transaction.Commit();
return Ok();
}
catch (Exception)
{
transaction.Rollback();
throw;
}
}
}

how to catch exception in spring boot rest api

i have a restcontroller with following Code
#RequestMapping(method = RequestMethod.POST, value = "/student")
public void addTopic(#RequestBody Student student) {
student.setPassword(bCryptPasswordEncoder.encode(student.getPassword()));
studentService.addStudent(student);
}
but if the json data doesn't match the Student object, or is wrong formatted an com.fasterxml.jackson.core.JsonParseException: Unexpected character ('"' (code 34)) ist thrown.
what is the best practice to prevent that
I've found that I need to catch JsonProcessingException (which JsonParseException extends from) in the #ExceptionHandler rather than JsonParseException
#ControllerAdvice
public class FeatureToggleControllerAdvice {
#ExceptionHandler(JsonProcessingException.class)
public ResponseEntity<JSONAPIDocument> handleJsonParseException(JsonProcessingException ex) {
final Error error = new Error();
error.setId(UUID.randomUUID().toString());
error.setStatus(HttpStatus.BAD_REQUEST.toString());
error.setTitle(ex.getMessage());
return new ResponseEntity<>(JSONAPIDocument
.createErrorDocument(Collections.singleton(error)), HttpStatus.NOT_FOUND);
}
}
Using JsonParseException in the above sample and nothing is caught, but using JsonProcessingException works as expected.
Use Spring ExceptionHandler to do that
You could specify an ExceptionHandler based on Exception types and also apply the error codes you want to use.
#ExceptionHandler(JsonParseException.class)
public JacksonExceptionHandler {
public ResponseEntity<String> handleError(final Exception exception) {
HttpStatus status = HttpStatus.BAD_REQUEST;
if (exception != null) {
LOGGER.warn("Responding with status code {} and exception message {}", status, exception.getMessage());
return new ResponseEntity<>(exception.getMessage(), status);
}
}
Furthermore you could make use of javax.validation to validate the entity you receive and then Spring Boot will do all the validation automagically. Just add #Valid to the body.

Asserting Exceptions for private method in JUnit

private static String getToken(HttpClient clientInstance) throws badcredentailsexception{
try{
// some process here throws IOException
}
catch(IOexception e){
throw new badcredentailsexception(message, e)
}
}
Now I need to write Junit test for the above method, My Junit code for above function is below
#Test(expected = badcredentailsexception.class)
public void testGetTokenForExceptions() throws ClientProtocolException, IOException, NoSuchMethodException, SecurityException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException {
Mockito.when(mockHttpClient.execute(Mockito.any(HttpPost.class))).thenThrow(IOException.class);
// mocked mockHttpClient to throw IOException
final Method method = Client.class.getDeclaredMethod("getToken", HttpClient.class);
method.setAccessible(true);
Object actual = method.invoke(null, mockHttpClient);
}
But this test is not being passed, any improvements??
Can we check the exception thrown by private method from junit ??
First of all, it is an antipattern to test a private method. It is not part of your API. See the already linked question: Testing Private method using mockito
To answer your question: When invoking a method via Reflection and the invoked method throws an Exception, the Reflection API wraps the Exception into an InvocationTargetException. So you could catch the InvocationTargetException and inspect the cause.
#Test
public void testGetTokenForExceptions() throws Exception {
HttpClient mockHttpClient = mock(HttpClient.class);
when(mockHttpClient.execute(any(HttpPost.class))).thenThrow(IOException.class);
Method method = Client.class.getDeclaredMethod("getToken", HttpClient.class);
method.setAccessible(true);
try {
method.invoke(null, mockHttpClient);
fail("should have thrown an exception");
} catch (InvocationTargetException e) {
assertThat(e.getCause(), instanceOf(BadCredentialsException.class));
}
}
You couldn't test private methods with JUnit or even with Mockito framework.
You could find more details in this question: Testing Private method using mockito
If you really need to test this private method, you should use PowerMock framework.

Junit test for Exception

I try to test my Exception JUnit and the test doesn't pass I have this error trace :
org.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run(JUnitAndHigherRunnerImpl.java:37)
and
org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62)
and here is my code :
PatientEntityFacade pef = new PatientEntityFacade();
Mockito.when(pef.findByNumber(5555)).thenReturn(patientEntity);
#Rule
public ExpectedException thrown = ExpectedException.none();
#Test
public void shouldThrow() throws PatientNotFoundException
{
thrown.expect(PatientNotFoundException.class);
thrown.expectMessage("personalized exception no patient found");
try {
pef.findByNumber(5555);
} catch (com.patient.facade.PatientNotFoundException e) {
e.printStackTrace();
}
}
If you watn to test your Exception, then do it the right way.
Define when Exception should be thrown.
in #BeforeClass if every Method should
in #Test-method if only this Method should throw it.
Notice, that you can use any(X.class) if other methods got other values for it.
DonĀ“t try-catch in unit-tests.
Catch it this way and if there is no Exception, the test will fail.
#Test(expected = PatientNotFoundException.class)
public void shouldThrow()
pef.findByNumber(5555);
}