我有一个运行良好的 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 个符合自动装配资格的 bean
候选人。依赖注释:
{@org.springframework.beans.factory.annotation.Autowired(必需= true)}
我不明白为什么我会收到这个错误。
您需要用注释来注释测试SpringBootTest
让 spring 初始化一个应用程序上下文
https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html#boot-features-testing-spring-boot-applications 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]时,创建的mock实例也会被
注射。每个测试方法后模拟 bean 会自动重置
see 嘲笑和监视 Bean https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html#boot-features-testing-spring-boot-applications-mocking-beans
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)