Using ReflectionTestUtils.setField () in Junit testing

I'm new to JUnittesting, so I have a question. Can someone tell me why we are using ReflectionTestUtils.setField()

Junit with an example in our testing.

+9


source to share


2 answers


As mentioned in the comment, the Java docs explain the usage very well. But I want to give you a simple example as well.

Let's say you have an Entity class with private or protected field access and no setter method provided .

@Entity
public class MyEntity {

   @Id
   private Long id;

   public Long getId(Long id){
       this.id = id;
   }
}

      

In your test class, you cannot install id

yours entity

due to the missing install method.

Using ReflectionTestUtils.setField

you can do this for testing purposes:



ReflectionTestUtils.setField(myEntity, "id", 1);

      

Parameters are described:

public static void setField(Object targetObject,
                            String name,
                            Object value)
Set the field with the given name on the provided targetObject to the supplied value.
This method delegates to setField(Object, String, Object, Class), supplying null for the type argument.

Parameters:
targetObject - the target object on which to set the field; never null
name - the name of the field to set; never null
value - the value to set

      

But try it and read the docs .

+14


source


this is very useful when we want to write a unit test such as:



class A{
   int getValue();
}

class B{
   A a;
   int caculate(){
       ...
       int v = a.getValue();
       ....
   }
}

class ServiceTest{
   @Test
   public void caculateTest(){
       B serviceB = new B();
       A serviceA = Mockito.mock(A.class);
       Mockito.when(serviceA.getValue()).thenReturn(5);
       ReflectionTestUtils.setField(serviceB, "a", serviceA);
   } 
}

      

0


source







All Articles