我有一个运行良好的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);
}
}
我得到这个错误
我不明白为什么我会收到此错误。
最佳答案
您需要使用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负责模拟处理
见Mocking and spying beans
关于spring-boot - 测试期间不满意的依存关系,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45088711/