gpt4 book ai didi

spring-boot - 测试期间不满意的依存关系

转载 作者:行者123 更新时间:2023-12-04 17:07:18 26 4
gpt4 key购买 nike

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

我在构造函数上使用 Autowiring

@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: Error creating bean with name 'com.sonos.arcor.service.AddressServiceTest': Unsatisfied dependency expressed through field 'service'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type ''com.sonos.arcor.service.AddressService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}



我不明白为什么我会收到此错误。

最佳答案

您需要使用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负责模拟处理

When [@MockBean is]used on a field, the instance of the created mock will also be injected. Mock beans are automatically reset after each test method



Mocking and spying beans

关于spring-boot - 测试期间不满意的依存关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45088711/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com