ExampleRepository
注释注入到测试类中的 @Autowired
运行良好,但是注入服务类是空的。为什么会发生这种情况?如何解决?
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());
}
// ...
}
答案 0 :(得分:0)
将@Repository
注释添加到界面ExampleRepository