I want to test some class.That class have boolean field with @Resource.I can't mock this field. Therefor it give test failed with some error.if anyone can tell me how can I test this class.
This is my java class
public class RefreshHandlerImpl implements RefreshHandler
{
@Resource(name = "readOnlyMode")
private Boolean readOnlyMode;
@Override
public ContactBedRefreshResult refreshContactsAndBeds(final Unit unit, final boolean hasWritableTransaction)
throws RequiresWritableTransactionException
{
if (!isReadOnlyMode())
{
//some code here
}
}
private boolean isReadOnlyMode()
{
return readOnlyMode;
}
}
I try to mock "readOnlyMode" field.But it give error.
org.mockito.exceptions.base.MockitoException: Cannot mock/spy class java.lang.Boolean Mockito cannot mock/spy following: - final classes - anonymous classes - primitive types
This is my testng test class
public class RefreshHandlerImplTest
{
@Mock(name = "readOnlyMode")
private Boolean readOnlyMode;
@InjectMocks
private RefreshHandlerImpl refreshHandlerImpl;
@BeforeMethod
public void setUp() throws Exception {
initMocks(this);
}
@Test
public void testRefreshContactsAndBeds_ReturnsZeroContactsWhenCollaboratorsDoes()
throws Exception
{
ContactBedRefreshResult result = refreshHandlerImpl.refreshContactsAndBeds(unit, true);
assertThat(result.getContacts()).isEmpty();
}
}
Can I use reflection and then how it use?I can't change my java class.Only can change test class.
I fixed the issue using org.springframework.test.util.ReflectionTestUtils
I removed
@Mock(name = "readOnlyMode") private Boolean readOnlyMode;
and usedReflectionTestUtils.setField(refreshHandlerImpl,RefreshHandlerImpl.class,"readOnlyMode",true,Boolean.class);
in my @BeforeMethod method. This is my test class,