我的任务是编写 JUnit 类。为此,我需要创建一个对象,该对象实现一个扩展org.springframework.data.jpa.repository.JpaRepository(称为“KanjiRepo”)的接口(interface),但此应用程序中没有任何类实际实现< i>KanjiRepo.
所有实现 KanjiRepo 的对象似乎都是通过 @Autowiring 创建的,而不是使用 new。
KanjiRepo 接口(interface)是仅具有接口(interface)的包的成员,并且它们都扩展org.springframework.data.jpa.repository.JpaRepository。
[问题]我认为我不明白这个问题。有人可以告诉我我刚才所说的听起来是否正确。在我的 junit 中,我是否还使用 @Autowire 创建在与 KanjiRepo 相同的包中实现接口(interface)的对象?最后一步需要维护 2 个单独的应用程序上下文 ?
最佳答案
我认为在您的测试类中 Autowiring KanjiRepo 就足够了,除非您将存储库注释为 @Repository。
@Repository
public interface KanjiRepo extends JpaRepository....
如果您在 KanjiRepo 之上有 @Repository 注释,并且您将主类或配置类注释为自动扫描 Bean; spring 将成功处理创建和 Autowiring bean。
请检查组件扫描
@SpringBootApplication
// or @ComponentScan
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
然后,您可以使用以下代码创建测试类;
@Autowired
KanjiRepo repo;
@Test
public void testFindById() {
Kanji instance = repo.findById(0L);
assert.....
}
应该没问题。
Can the application and JUnit share the same configuration files?
事实上,确实如此。但是,如果您进行组件扫描,则不必担心这一点。 Spring 将处理您的 bean 所在位置,并且它应该成功 Autowiring 。
block 引用>do I also use @Autowire to create objects that implement the interfaces in the same package as KanjiRepo?
Spring 将进行组件扫描并找到您的存储库所在的位置,因此,您不必担心存储库的位置。
关于java - 通过 JUnit 中的 Autowiring 创建实现 JpaRepo 接口(interface)的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58018407/