Home > Net >  ReflectionTestUtils set field method
ReflectionTestUtils set field method

Time:06-22

Is there a way to use ReflectionTestUtils to set the return value of a method inside a field that represents a class to a mocked value instead of mocking the entire field? I was trying .setField(), but that only seems to work for the entire field. If there isn't, what would be a good substitute? Example of what I mean below:

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
        ...
    }
}

The class that is called in the field is very complicated, but there is a very simple public method that acts as the root of the class, and I want to set that to a specific value. The class itself does not have a constructor, so I need a way to get around that.

This is a spring boot project written in Java, and I need to use ReflectionTestUtils to be able to pass an argument into Mockito mock

CodePudding user response:

You can use @Spy on field and inject spied field using ReflectionTestUtils. Something like this

@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
    }
}

CodePudding user response:

java.reflection made this much easier to do, article for more info linked here: https://www.geeksforgeeks.org/reflection-in-java/

  • Related