user710818
user710818

Reputation: 24288

How to create instance of org.springframework.dao.DataAccessException?

I need to create JUnit test for handling of DataAccessException,

but when I try:

            throw new DataAccessException();

Receive:

 Cannot instantiate the type DataAccessException

Why? What can I do? Thanks.

Upvotes: 12

Views: 20779

Answers (5)

Roger Lindsjö
Roger Lindsjö

Reputation: 11553

DataAccessException is an abstract class and can not be instantiated. Instead use one of the concrete classes such as new DataRetrievalFailureException("this was the reason") or create your own:

throw new DataAccessException("this was the reason") {};

And you get an anonymous class derived from the DataAccessException.

Upvotes: 28

Navankur Chauhan
Navankur Chauhan

Reputation: 417

Instead of Using TransientDataAccessException.class , this can be used

 doThrow(new TransientDataAccessException("Oops! Something went wrong.") {}).when(myMock).callSomeMethod(param1,param2);

Upvotes: 1

David Arevalo
David Arevalo

Reputation: 19

I needed to return Mono.error with a DataAccessException in my test mock. I instanciated a anonymous class of the abstract class and it worked for me:

Mono.error(new DataAccessException("exception message"){})

Upvotes: 0

Alireza
Alireza

Reputation: 104900

If you looking into source code, you will notice it's an abstract class, look into that:

package org.springframework.dao;

import org.springframework.core.NestedRuntimeException;

public abstract class DataAccessException extends NestedRuntimeException {
    public DataAccessException(String msg) {
        super(msg);
    }

    public DataAccessException(String msg, Throwable cause) {
        super(msg, cause);
    }
}

And as you know abstract classes can not be extended...

But you can use it in other ways, this is one way to use it for example:

public interface ApiService {
    Whatever getSomething(Map<String, String> Maps) throws DataAccessException;
}

Upvotes: 0

Kazekage Gaara
Kazekage Gaara

Reputation: 15052

Why?

Simply because DataAccessException is abstract class. You cannot instantiate an abstract class.

What can I do?

If you check the hierarchy:

extended by java.lang.RuntimeException
              extended by org.springframework.core.NestedRuntimeException
                  extended by org.springframework.dao.DataAccessException

Since NestedRuntimeException is also abstract, you can throw a new RuntimeException(msg);(which is not recommended). You can go for what the other answer suggests - Use one of the concrete classes.

Upvotes: 6

Related Questions