【问题标题】:How to unit test Boolean field with @Resource如何使用@Resource 对布尔字段进行单元测试
【发布时间】:2018-10-25 23:14:21
【问题描述】:

我想测试一些类。那个类有带有@Resource 的布尔字段。我不能模拟这个字段。因此它给出了一些错误的测试失败。如果有人可以告诉我如何测试这个类。

这是我的java类

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;
  }

}

我尝试模拟“readOnlyMode”字段。但它给出了错误。

org.mockito.exceptions.base.MockitoException: 无法模拟/监视类 java.lang.Boolean Mockito 无法模拟/监视以下内容: - 最后的课程 - 匿名类 - 原始类型

这是我的 testng 测试类

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();
 }
}

我可以使用反射,然后它是如何使用的?我无法更改我的 java 类。只能更改测试类。

【问题讨论】:

  • 您使用的是哪个版本的 Mockito?
  • @Rcordoval 我用的是 1.9.5
  • 我尝试使用 ReflectionTestUtils.setField(false,RefreshHandlerImpl.class,"readOnlyMode",false,Boolean.class);在测试类中。但它也失败了
  • Mockito 不允许,但版本 2+ 允许。

标签: java unit-testing mockito testng


【解决方案1】:

我使用 org.springframework.test.util.ReflectionTestUtils 解决了这个问题

我删除了@Mock(name = "readOnlyMode") private Boolean readOnlyMode; 并在我的@BeforeMethod 方法中使用ReflectionTestUtils.setField(refreshHandlerImpl,RefreshHandlerImpl.class,"readOnlyMode",true,Boolean.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();
 }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-10-17
    • 2018-09-27
    • 1970-01-01
    • 2019-12-01
    • 2012-01-08
    • 1970-01-01
    • 2020-01-17
    • 2014-01-22
    相关资源
    最近更新 更多