簡體   English   中英

如果我有 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() 就可以了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM