测试期间不满意的依赖性

rob*_*del 5 spring-boot spring-boot-test

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

我在构造函数上使用autowired

@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);
    }
    ...
}
Run Code Online (Sandbox Code Playgroud)

当我尝试运行基本测试时

@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);

    }
}
Run Code Online (Sandbox Code Playgroud)

我收到这个错误

org.springframework.beans.factory.UnsatisfiedDependencyException:创建名为'com.sonos.arcor.service.AddressServiceTest'的bean时出错:通过字段'service'表示的不满意的依赖关系; 嵌套异常是org.springframework.beans.factory.NoSuchBeanDefinitionException:没有类型''com.sonos.arcor.service.AddressService'的限定bean可用:预期至少有1个bean有资格作为autowire候选者.依赖注释:{@ org.springframework.beans.factory.annotation.Autowired(required = true)}

我不明白为什么我会收到这个错误.

Mat*_*nkt 11

您需要对测试进行注释,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
}
Run Code Online (Sandbox Code Playgroud)

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

Spring负责模拟处理

在字段上使用[@MockBean]时,也会注入创建的模拟的实例.每种测试方法后,模拟豆都会自动重置

看到嘲弄和间谍豆