如果我使用@Spy,它将帮助我模拟方法。但它不适用于私有变量初始化
FieldSetter.setField(discoveryService, discoveryService.getClass().getDeclaredField("discoveryURL"), discoveryUrl);如果我删除@spy,FieldSetter就会初始化模拟私有变量。我用@spy编写的代码:
@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行工作正常。为什么我有@spy,FieldSetter就不能工作。如何让FieldSetter也为@spy工作?
发布于 2021-06-22 00:23:31
不要使用FieldSetter,使用ReflectionTestUtils.setField()就可以了。
发布于 2020-07-09 18:18:13
您可以使用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");
}https://stackoverflow.com/questions/62807985
复制相似问题