import com.google.cloud.spanner.Key;
import com.google.common.flogger.FluentLogger;
import org.springframework.cache.annotation.Cacheable;
import com.google.cloud.spring.data.spanner.repository.SpannerRepository;
import org.springframework.stereotype.Repository;
import java.util.Optional;
@Repository
public interface OrganisationRepository extends SpannerRepository<Organisation, Key> {
@Cacheable("OrgCache")
Organisation findByCode(String orgCode);
default Organisation getByCode(String orgCode, Runnable loggedErrorMessage) {
return Optional.ofNullable(this.findByCode(orgCode))
.orElseThrow(() -> {
loggedErrorMessage.run();
return new ResourceNotFoundException(ErrorCode.ORG_NOT_FOUND.getErrorData(orgCode));
});
}
}
How do I write a unit test for getByCode? I'm tied up in knots between SpannerRepository and the limits of what DataJpaTest supports and can't see a way through... best attempt so far:
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.*;
@ExtendWith(SpringExtension.class)
@DataJpaTest
class OrganisationRepositoryTest {
@Autowired
OrganisationRepository organisationRepository;
@Test
void getByCode_LogsErrorMessageWhenNotFound() {
StringBuilder sb = new StringBuilder();
organisationRepository.getByCode("unknownOrgCode", ()-> sb.append("the error I want to log"));
assertThat(sb.toString()).isEqualTo("the error I want to log");
}
}
This test fails with:
Caused by: java.lang.ClassNotFoundException: org.springframework.jdbc.core.ConnectionCallback