【问题标题】:I can't autowire Service class in Spring Boot Test我无法在 Spring Boot Test 中自动装配服务类
【发布时间】:2022-01-17 12:34:48
【问题描述】:

我创建了使用 jdbc 处理 DB 的 Dao Repository。

我在我的服务类中自动装配了这个存储库。

然后我尝试在我的测试类中自动装配我的服务类。

@SpringBootTest
public class ServiceTest {
   @MockBean
   private Dao dao;

   @Autowired
   private Service service;

   @Test
   void whenSomething_thanSomething() {
      when(Dao.getStatus(anyString())).thenReturn("green");
      assertEquals(0, service.getStatus(""));
   }

   //other tests...

}

@Service
public class Service {
   private DaoImpl daoImpl;

   @Autowired
   public Service(DaoImpl daoImpl) {
      this.daoImpl = daoImpl;
   }

   //...

}

@Repository
public class DaoImpl omplements Dao {
   private NamedParameterJdbcOperations jdbc;
   
   @Autowired
   public DaoImpl(NamedParametedJdbcOperations jdbc) {
      this.jdbc = jdbc;
   }

   //...

}

当我开始测试时,我得到下一个错误:

Service中构造函数的参数0需要一个找不到的DaoImpl类型的bean。

我该如何解决我的问题?

【问题讨论】:

    标签: spring-boot mockito autowired spring-boot-test springmockito


    【解决方案1】:

    由于您在服务类中注入 DaoImpl,因此您可能打算模拟 DaoImpl 而不是 Dao

    @SpringBootTest
    public class ServiceTest {
       @MockBean
       private DaoImpl daoImpl;
       ...
    }
    

    【讨论】:

      猜你喜欢
      • 2020-03-24
      • 2023-03-21
      • 2020-04-29
      • 1970-01-01
      • 2019-01-10
      • 2018-12-27
      • 2021-04-02
      • 2017-09-07
      • 2020-08-26
      相关资源
      最近更新 更多