我想对我的JDBI映射器类进行单元测试,因为并非所有人都可以进行简单的属性映射。
我的测试类看起来如下:
public class IdentRuleMapperTest {
@Mock
ResultSet resultSet;
@Mock
ResultSetMetaData resultSetMetaData;
@Mock
StatementContext ctx;
IdentRuleMapper mapper;
@Before
public void setup() {
mapper = new IdentRuleMapper();
}
@Test
public void mapTest() throws SQLException {
Mockito.when(resultSet.getString("ID")).thenReturn("The ID");
Mockito.when(resultSet.getString("NAME")).thenReturn("The name");
Mockito.when(resultSet.getString("REGULATION")).thenReturn("CRS");
Mockito.when(resultSet.getString("JSON_ACTIONS_STRING")).thenReturn("the json string");
IdentRule identRule = mapper.map(0, resultSet, ctx);
}
}
测试将NPE抛到行
Mockito.when(resultSet.getString("ID")).thenReturn("The ID");
任何人都可以向我指出为什么这不起作用?
答案 0 :(得分:2)
The annotation @Mock
does not create the mock objects by itself. You have to add Mockito's JUnit rule as a field to your test
@Rule
public MockitoRule rule = MockitoJUnit.rule();
or use its JUnit runner
@RunWith(MockitoJUnitRunner.class)
public class IdentRuleMapperTest {
...
or create the mocks in an @Before
method using MockitoAnnotations
@Before
public void initMocks() {
MockitoAnnotations.initMocks(this);
}
答案 1 :(得分:0)
在设置模拟对象的期望时,使用Matchers进行参数匹配。
Mockito.when(resultSet.getString( Matchers.eq("ID"))).thenReturn("The ID");