如果我有 Mockito.Spy()/@Spy 不能与 FieldSetter 一起正常工作?如何结合使用@Spy 和FieldSetter?

If I have Mockito.Spy()/@Spy doesn't work properly with FieldSetter ? How to work use @Spy and FieldSetter Combinedly?

如果我使用@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 工作?

您可以使用 org.springframework.test.util.ReflectionTestUtils

为实例的私有属性注入值
@Service
public class SampleDiscoveryService{

    @Value("${props.discoveryUrl}")
   private String discoveryUrl;
}

假设上面是服务 class,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");
    }


不要使用 FieldSetter,使用 ReflectionTestUtils.setField() 就可以了。