1

ExampleRepository injected by @Autowired annotation into test class works well, but injected into service class is null. Why does it happen and how can I fix it?

Repository class

public interface ExampleRepository extends JpaRepository<Example, Long> {

    // ...
}

Service class

@Service
public class Feed {

    @Autowired
    private ExampleRepository exampleRepository;

    private File file;

    public Feed(String file) {
        this.file = new File(file);
    }

    // ...
}

Test class

@ExtendWith(SpringExtension.class)
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
@SpringBootTest
@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
@Rollback(false)
public abstract class ExampleTests {

    @Autowired
    private ExampleRepository exampleRepository;

    @BeforeEach
    public void setUp() {
        restoreInitialData();
    }

    protected void restoreInitialData() {
        this.exampleRepository.deleteAll();
    }

    @Test
    public void test() {
        Feed feed = new Feed("example.json");
        Optional<Example> example = feed.ingest();
        assertTrue(example.isPresent());
    }

    // ...
}
Kamil Pajak
  • 340
  • 2
  • 13

1 Answers1

0

Add the @Repository annotation to the interface ExampleRepository

soorapadman
  • 4,451
  • 7
  • 35
  • 47
Lara
  • 21
  • 1
  • No it doesn't as it is a Spring Data JPA repository. – M. Deinum Nov 14 '17 at 11:16
  • Is JpaRepository not part of Spring Data JPA? – Lara Nov 14 '17 at 11:24
  • Yes it is but you don't need `@Repository` for them to be detected. Spring Data automatically detects repositories extending the Spring Data `Repository` interface (which is one of the super interfaces of `JpaRepository`. – M. Deinum Nov 14 '17 at 11:31