I am trying to figure out a way to create a mock implementation of my Mongo DB repository that used a HashMap under the covers. This way, I wouldn't have to mock out every single database call and could simply let the database act as a black box and just check the results at the end.
Asked
Active
Viewed 744 times
2 Answers
1
I found this article here to be very helpful: http://www.heavyweightsoftware.com/blog/creating-a-mock-class-for-unit-testing-with-a-spring-repository/
In short, here's the implementation from that page:
public class MockWidgetRepository implements WidgetRepository{
Map<Long, Widget> backingMap = new HashMap<>();
@Override
public <S extends Widget> S save(S entity) {
backingMap.put(entity.getId(), entity);
return entity;
}
@Override
public <S extends Widget> List<S> save(Iterable<S> entites) {
return null;
}
@Override
public Widget findOne(Long id) {
Widget result = backingMap.get(id);
return result;
}
@Override
public boolean exists(Long aLong) {
return false;
}
@Override
public List<Widget> findAll() {
List<Widget> result = new ArrayList<>();
result.addAll(backingMap.values());
return result;
}
@Override
public Iterable<Widget> findAll(Iterable<Long> longs) {
return null;
}
@Override
public long count() {
return 0;
}
@Override
public void delete(Long aLong) {
}
@Override
public void delete(Widget entity) {
}
@Override
public void delete(Iterable<? extends Widget> entities) {
}
@Override
public void deleteAll() {
backingMap.clear();
}
@Override
public List<Widget> findAll(Sort sort) {
return null;
}
@Override
public Page<Widget> findAll(Pageable pageable) {
return null;
}
@Override
public <S extends Widget> S insert(S entity) {
return null;
}
@Override
public <S extends Widget> List<S> insert(Iterable<S> entities) {
return null;
}
@Override
public <S extends Widget> S findOne(Example<S> example) {
return null;
}
@Override
public <S extends Widget> List<S> findAll(Example<S> example) {
return null;
}
@Override
public <S extends Widget> List<S> findAll(Example<S> example, Sort sort) {
return null;
}
@Override
public <S extends Widget> Page<S> findAll(Example<S> example, Pageable pageable) {
return null;
}
@Override
public <S extends Widget> long count(Example<S> example) {
return 0;
}
@Override
public <S extends Widget> boolean exists(Example<S> example) {
return false;
}
}

Thom
- 14,013
- 25
- 105
- 185
-
To be on the safe side, I'd create a copy of the entity in the `save` method, just to make sure the client does not ignore the return value (by assuming it is the same object as the one passed in). You could also use a counter to provide ids for new entities etc., depending on how thorough the tests are going to be – crizzis Apr 02 '18 at 18:32
0
You can use Fongo (https://github.com/fakemongo/fongo) or https://github.com/flapdoodle-oss/de.flapdoodle.embed.mongo. The latter one is used by spring framework as an embedded in-memory Mongodb.

Jas Bali
- 241
- 2
- 10