【问题标题】:Unsatisfied dependency during test测试期间不满足的依赖关系
【发布时间】:2017-12-18 17:07:14
【问题描述】:

我有一个运行良好的 spring boot 2.0.0 M2 应用程序。

我在构造函数上使用自动装配

@RequestMapping(value = "/rest")
@RestController
public class AddressRestController extends BaseController{

    private final AddressService AddressService;

    @Autowired
    public AddressRestController(final AddressService AddressService) {
        this.AddressService = AddressService;
    }
    ...
}

@Service
public class AddressServiceImpl extends BaseService implements AddressService {

    @Autowired
    public AddressServiceImpl(final AddressRepository AddressRepository) {
        this.AddressRepository = AddressRepository;
    }

    private final AddressRepository AddressRepository;
    ...
}


public interface AddressRepository extends JpaRepository<Address, Integer>, AddressRepositoryCustom {

}

@Repository
public class AddressRepositoryImpl extends SimpleJpaRepository implements AddressRepositoryCustom {
    @PersistenceContext
    private EntityManager em;

    @Autowired
    public AddressRepositoryImpl(EntityManager em) {
        super(Address.class, em);
    }
    ...
}

当我尝试运行基本测试时

@RunWith(SpringJUnit4ClassRunner.class)
public class AddressServiceTest {

    @Autowired
    private AddressService service;

    @MockBean
    private AddressRepository restTemplate; 

    @Test
    public void getAddress(){

        MockitoAnnotations.initMocks(this);

        Pageable page = PageRequest.of(0, 20);

        Page<Address> pageAdr = mock(Page.class);

        given(this.restTemplate.findAll(page)).willReturn(pageAdr);

        Page<AddressDto> pageDto = service.getAddress(page);

    }
}

我收到此错误

org.springframework.beans.factory.UnsatisfiedDependencyException: 创建具有名称的 bean 时出错 'com.sonos.arcor.service.AddressServiceTest':不满足的依赖关系 通过现场“服务”表达;嵌套异常是 org.springframework.beans.factory.NoSuchBeanDefinitionException: 否 ''com.sonos.arcor.service.AddressService' 类型的合格 bean 可用:预计至少有 1 个符合 autowire 条件的 bean 候选人。依赖注解: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

我不明白为什么会出现这个错误。

【问题讨论】:

    标签: spring-boot spring-boot-test


    【解决方案1】:

    您需要使用 SpringBootTest 注释测试,以便 spring 初始化应用程序上下文

    https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html#boot-features-testing-spring-boot-applications

    @SpringBootTest
    @RunWith(SpringJUnit4ClassRunner.class)
    public class AddressServiceTest {
    // the remaining test
    }
    

    你也不需要MockitoAnnotations.initMocks(this);

    Spring 负责模拟处理

    当 [@MockBean is] 在字段上使用时,创建的模拟实例也将被 注入。模拟 bean 在每个测试方法后自动重置

    Mocking and spying beans

    【讨论】:

      猜你喜欢
      • 2017-06-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-15
      • 1970-01-01
      • 1970-01-01
      • 2016-07-10
      • 2021-01-12
      相关资源
      最近更新 更多