簡體   English   中英

ReflectionTestUtils 設置字段方法

[英]ReflectionTestUtils set field method

有沒有辦法使用 ReflectionTestUtils 將表示類的字段內的方法的返回值設置為模擬值而不是模擬整個字段? 我正在嘗試 .setField(),但這似乎只適用於整個領域。 如果沒有,什么是好的替代品? 我在下面的意思的例子:

public class Example() {
    private ClassField field;
    
    public methodThatUsesField() {

        methodReturnType type = field.method(); // I was trying to call .setField() to change the field's method to a mocked value, but can't figure out how to do it
        ...
    }
}

在字段中調用的類非常復雜,但是有一個非常簡單的公共方法充當類的根,我想將其設置為特定值。 類本身沒有構造函數,所以我需要一種方法來解決這個問題。

這是一個用 Java 編寫的 spring boot 項目,我需要使用 ReflectionTestUtils 才能將參數傳遞給 Mockito mock

您可以使用Mockito.spy(field)並使用ReflectionTestUtils注入間諜字段。 像這樣的東西

@SpringBootTest
class ExampleTest {

    @Autowired
    private Example example;

    @Autowired
    private ClassField field;

    @Test
    void testMethodThatUsesField() {
        ClassField spiedField = Mockito.spy(field);
        Mockito.when(spiedField.method()).thenReturn(methodReturnTypeValue);
        ReflectionTestUtils.setField(example, "field", spiedField);
        example.methodThatUsesField();
     // assertions
    }
}

暫無
暫無

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

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