如何测试与存储库交互的服务?

时间:2018-12-29 11:51:22

标签: spring mockito

我想测试register(...)中定义的ObserverService方法。我所拥有的是:

public interface ObserverRepository extends CrudRepository<MatchObserverList, String> {}

服务:

@Service
public class ObserverServiceImp implements ObserverService {

    private ObserverRepository observerRepository;

    private SensorService sensorService;

    @Autowired
    public ObserverServiceImp(SensorService sensorService, ObserverRepository observerRepository) {
        this.observerRepository = observerRepository;
        this.sensorService = sensorService;
    }

    @Override
    public void register(MatchObserver observer, String[] sensor_IDs) {

        MatchObserverList list;

        for(String id: sensor_IDs){
            Optional<MatchObserverList> optional = observerRepository.findById(id);
            if(optional.isPresent()){
                list = optional.get();
                list.getObservers().add(observer);
            }else{
                list = new MatchObserverList(id);
                list.getObservers().add(observer);
            }

            observerRepository.save(list);
        }

    }
}

和测试班:

@RunWith(SpringRunner.class)
public class MatchObserverServiceTest {

    @Mock
    ObserverRepository repository;

    @InjectMocks
    ObserverServiceImp service;

    MatchObserver o1;
    String[] o1_list;

    MatchObserver o2;
    String[] o2_list;

    @Before
    public void setUp() {
        o1 = new MatchObserver(new TokenFCM("aav"));
        o1_list = new String[]{"111", "222", "333"};

        o2 = new MatchObserver(new TokenFCM("bbb"));
        o2_list = new String[]{"222", "333", "444"};

    }

    @Test
    public void testRegisterObservers(){
        service.register(o1,o1_list);
        service.register(o2,o2_list);

        Assert.assertEquals(2, repository.count());
    }

    @After
    public void cleanUp(){
        repository.deleteAll();
    }
}

repository.count()每次返回0。怎么了?

0 个答案:

没有答案