给私有属性赋值工具类及方法:
ReflectionTestUtils.setField(userService, field_name, field_value);
在不启动Spring 容器的情况下,如何给Mock的对象的私有属性赋值?我们可以直接使用spring-test包中的工具类:
public class UnitTest{
@Mock
private UserDao userDao;
@InjectMocks
private UserService userService;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
ReflectionTestUtils.setField(userService,"magic_val",10);
}
// other test code
}
UserService:
@Service
public class UserService{
@Value("${magic.value:200}")
private Integer magic_val;
@AutoWired
private UserDao userDao;
//more code
}