mercredi 15 mai 2019

Is that possible to set the properties for the mock object before injectMock

I try to set some properties for the mock object before injecting them to the test class, but it doesn't work;

here is my code:

public class MyClass {

    @Autowired
    private MyProperties myProperties;

    @Autowired
    private Properties properties;

    private final String id;
    private final String name;


    public MyClass(MyProperties myProperties){
        id = myProperties.getId();
        name = myProperties.getName();
    }

    public String Info(){
        return properties.getAddress();
    }
}

here is my test:

public class TestClass {

@Mock
private MyProperties myProperties;

@Mock
private Properties properties;

@InjectMocks
private MyClass testObject = new MyClass(myProperties);

@Before
public void setUp(){
    when(myProperties.getId()).thenReturn("1");
    when(myProperties.getUser()).thenReturn("user");
}

@Test
public void InfoTest(){
    when(properties.getAddress()).thenReturn("address");
    assertEquals("address", testObject.info());
}
}

It seems @injectMocks happens before setUp() method and @InjectMocks already help to instantiate an object of MyClass before when...thenReturn working, so it threw a NullPointerException

so, Is that possible to set the properties for the mock object before injectMock? anyone can help?

Aucun commentaire:

Enregistrer un commentaire