C
C
Clean Coder2020-11-12 14:16:08
Java
Clean Coder, 2020-11-12 14:16:08

How to quickly and efficiently mock relational databases for tests?

What approaches do you use?

I tried to do it through ArrayList, but it looks somehow not very good, and it takes a long time to write.

public class DatabaseMock implements DatabaseManager {

    private List<TableRecord> table = new ArrayList<TableRecord>() {{
        add(new TableRecord(1, "name", "description"));
    }};

    @Override
    public String getName(int id) {
        for (TableRecord tableRecord : table) {
            if (tableRecord.getId() == id) {
                return tableRecord.getName();
            }
        }
        return "Noname";
    }
}

Answer the question

In order to leave comments, you need to log in

3 answer(s)
I
illuzor, 2020-11-12
@iLLuzor

It is more convenient to wet through special tools. For example, using the mockito library

D
Dmitry Roo, 2020-11-12
@xez

mockito is pretty handy for making stubs. But this is more for unit tests.
or
testcontainers -- for full integration tests. It is necessary that the docker was installed on the machine. This is not a database emulation - this is a real database being raised in docker. After the tests, it all dies.

B
BorLaze, 2020-11-12
@BorLaze

Personally, I prefer tools like EmbeddedPostgres.
Longer than mocks, of course, but this is almost a complete analogue of work in production - the database has risen, initialized with data, we have performed the actions we need (the same insert or select of any complexity), and died.
For mocks are, of course, good, but what if we have already changed the structure of the database, but not the tests?
The code works with old mocks, everything is fine - but in real work, bang, and "everyone died" ...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question