如何测试调用Repository的方法?

时间:2016-05-04 16:14:11

标签: java arraylist junit repository spring-data

我是编写Junit测试的新手。我想知道如何测试如下方法:

    @Transactional
    public List<Dog> getAllDogs() {
        Iterable<Dog> allDogs = dogRepository.findAll();
        return Lists.newArrayList(allDogs);
    }

DogRepository Class (注意继承findall()方法)

public interface DogRepository extends CrudRepository<Dog, Integer> {


}

1 个答案:

答案 0 :(得分:0)

您模拟存储库,将此模拟注入服务,然后调用测试中的方法。

Mockito的例子:

DogRepository mockRepo = mock(DogRepository.class);

Dog fido = new Dog("Fido");
Dog brutus = new Dog("Brutus");
when(mockRepo.findAll()).thenReturn(Arrays.asList(fido, brutus));

DogService service = new DogService(mockRepo);
List<Dog> result = service.getAllDogs();
assertEquals(Arrays.asList(fido, brutus), result);