How to unit test Boolean field with @Resource

2019-08-02 09:37发布

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.

1条回答
做个烂人
2楼-- · 2019-08-02 10:00

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,

public class RefreshHandlerImplTest
{
 @InjectMocks
 private RefreshHandlerImpl refreshHandlerImpl;

 @BeforeMethod
 public void setUp() throws Exception {
  initMocks(this);
  ReflectionTestUtils.setField(refreshHandlerImpl,RefreshHandlerImpl.class,"readOnlyMode",true,Boolean.class);
 }

 @Test
 public void testRefreshContactsAndBeds_ReturnsZeroContactsWhenCollaboratorsDoes() throws Exception
 {
   ContactBedRefreshResult result = 
   refreshHandlerImpl.refreshContactsAndBeds(unit, true);
   assertThat(result.getContacts()).isEmpty();
 }
}
查看更多
登录 后发表回答