如果我使用@Spy,它将帮助我模拟方法。但它不适用于私有变量初始化
FieldSetter.setField(discoveryService, discoveryService.getClass().getDeclaredField("discoveryURL"), discoveryUrl);
如果我删除@sspy,FieldSetter将初始化mock私有变量。我与@speey:的代码
@InjectMocks
/*line 5*/ @Spy
private Class object;
@Test
void getFetchDiscoveryTest() throws IOException, NoSuchFieldException {
String discoveryUrl = "https://ffc-onenote.officeapps.live.com/hosting/discovery";
/*line 15*/ FieldSetter.setField(object, object.getClass().getDeclaredField("discoveryURL"), discoveryUrl);
/*line 16*/ doThrow(IOException.class).when(object).getBytes(any());
/*line 17*/ when(object.getBytes(any())).thenThrow(new IOException("IO issue"));
assertThrows(Exception.class, () -> object.getWopiDiscovery());
在这里,如果我轻击了5号线,那么15号线不起作用,16号线起作用。为什么如果我有@speey,FieldSetter就不起作用了。如何让FieldSetter也为@speey工作?
不要使用FieldSetter,使用ReflectionTestUtils.setField((就可以了。
您可以使用org.springframework.test.util.ReflectionTestUtils
为实例的私有属性注入值
@Service
public class SampleDiscoveryService{
@Value("${props.discoveryUrl}")
private String discoveryUrl;
}
假设上面是服务类,discoveryUrl
的值可以使用注入
@ExtendWith(MockitoExtension.class)
class SampleDiscoveryServiceTest {
@InjectMocks
private SampleDiscoveryService sampleDiscoveryService = null;
@BeforeEach
void setup() {
ReflectionTestUtils.setField(sampleDiscoveryService, "discoveryUrl", "https://ffc-onenote.officeapps.live.com/hosting/discovery");
}