Вопрос

I have a DAO-Layer which I want to test with JUnit. The test coverage is about 85%, so nearly every line of code is covered except the catch clauses for SQLException. I have no idea how I can provoke a SQLException for the snippet below:

Code coverage report
The only conceivable solution for me is to reset the value of the final variable SELECT_ALL_ATTR to something like: SELLLLLECT * FROM ATTRIBUTES; by using java reflection. I know that I can easily test exceptions by using the Mock framework. But I don't want to introduce Mock tests just for exception testing since everything else is tested with JUnit.

Is there a way other than java reflection?

Это было полезно?

Решение

It's not easy to simulate a sql exception in your case because all dependences are initiated by the dao itself. Maybe you can pass a fake Connection which throws a SqlException in some method?

Другие советы

I wrote a little tool for this http://melati.org/throwing-jdbc-4.1/index.html

This is a great use case for a mock library. I use mockito. Assuming you want to test the behavior of the clients of your DAO, you just mock it:

import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import junit.framework.Assert;
import org.junit.Test;
public class MockitoTest {
/** your dao, just putting some code here for an example */ 
class MyDAO {
    public List<SVCAttribute> selectAll(Connection con) throws DAOException {
        try {
            //your code..
        }catch(Exception ex) {
            throw new DAOException();
        }
        return new ArrayList<SVCAttribute>();
    }
}
@Test
public void testMe() throws Exception {
    MyDAO dao = mock(MyDAO.class);
    when(dao.selectAll(any(Connection.class))).thenThrow(DAOException.class);
    Connection con = getConnection();
    try {
        dao.selectAll(con);
        Assert.fail();
    }catch(Exception ex) {
        System.out.println("caught expected excetpion");
    }
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top