I am writing test cases for a legacy code which for some reason we dont want to change. The code is something like this
public class ToBeTested{
private static final String field1=SomeUtil.getProperty("somekey");
@AutoWired
Someservice service;
}
In my Junit I am using powermock with mockito and did something like this
public class myTestClass{
@Mock
SomeService service;
@InjectMock
ToBeTested tested;
}
However, InjectMocks fails to create the object for ToBeTested since the final fields are not provided
So I implemented a @BeforeClass and mocked the static method of SomeUtil. This works if i have only one test case. But for more than one test case, only one passes and others are failing with same error that
cannot instantiate @injectmocks field named you haven't provided the instance at field declaration
I have been able to resolve this by using something as below:
public class myTestClass{
@Mock
SomeService service;
ToBeTested tested;
@Before
public void setup(){
MockitoAnnotations.initMocks(this);
mockStatic(SomeUtil.class);
when(SomeUtil.getProperty(anyString())).thenReturn("test");
toBeTested=new ToBeTested(); Whitebox.setInternalState(toBeTested,"someService",someService);
}
}
However am not a fan of using reflection in Junit which WhiteBox does internally. Is there a better way to do this?
Aucun commentaire:
Enregistrer un commentaire