我尝试在将模拟对象注入测试类之前为模拟对象设置一些属性,但这不起作用
这是我的代码:
public class MyClass {
@Autowired
private MyProperties myProperties;
@Autowired
private Properties properties;
private final String id;
private final String name;
public MyClass(MyProperties myProperties){
id = myProperties.getId();
name = myProperties.getName();
}
public String Info(){
return properties.getAddress();
}
}
这是我的测试
public class TestClass {
@Mock
private MyProperties myProperties;
@Mock
private Properties properties;
@InjectMocks
private MyClass testObject = new MyClass(myProperties);
@Before
public void setUp(){
when(myProperties.getId()).thenReturn("1");
when(myProperties.getUser()).thenReturn("user");
}
@Test
public void InfoTest(){
when(properties.getAddress()).thenReturn("address");
assertEquals("address", testObject.info());
}
}
@injectMocks似乎发生在setUp()方法之前,而@InjectMocks已经帮助在... thenReturn之前实例化MyClass对象,因此它引发了NullPointerException
那么,是否有可能在injectMock之前设置模拟对象的属性?有人可以帮助吗?