【发布时间】: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