我在测试类中实例化时导致@Value注释返回null的服务中使用自动装配构造函数。自动装配依赖关系直接解决了问题,但该项目遵循使用基于构造函数的自动装配的约定。我的理解是,在测试类中实例化服务不是从Spring IoC容器创建的,它导致@Value返回null。有没有办法使用基于构造函数的自动装配从IoC容器创建服务,而无需直接访问应用程序上下文?Spring @Autowired构造函数在测试类中实例化时使@Value返回null
示例服务:
@Component
public class UpdateService {
@Value("${update.success.table}")
private String successTable;
@Value("${update.failed.table}")
private String failedTable;
private UserService userService
@Autowired
public UpdateService(UserService userService) {
this.userService = userService;
}
}
实例测试服务:
@RunWith(SpringJUnite4ClassRunner.class)
@SpringApplicationConfiguration(classes = {TestApplication.class})
@WebAppConfiguration
public class UpdateServiceTest {
private UpdateService updateService;
@Mock
private UserService mockUserService;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
updateService = new UpdateService(mockUserService);
}
}
如果你有'UpdateService' bean,只需'@ Autowired'它。 –
不幸的是,这并不能帮助我,因为我需要能够在测试类中使用模拟对象构建UpdateService。 – Alex
对,错过了。看看[这里](http://stackoverflow.com/questions/2457239/injecting-mockito-mocks-into-a-spring-bean)提示。 –