我正在尝试在 Spring Boot 中测试一些 dao 代码。这是我正在测试的课程:
@Repository
public class AreaDao
{
@Setter private JdbcTemplate jdbcTemplate;
@Setter private AreaMapper areaMapper;
@Getter @Setter private String sql;
public List getArea(String studioId)
{
String query = String.join(this.getSql(),studioId); // its throwing a NPE here
List areaList = jdbcTemplate.query(query, areaMapper);
return areaList;
}
}
变量 sql 正在从 bean xml 加载:
<bean id="AreaDao" class="com.studio.dao.AreaDao">
<property name="sql" value="SELECT DISTINCT(rGrp.GRP_N) AS AreaName
FROM DB.S_GRP rGrp
WHERE rGrp.STR_I = " />
<property name="jdbcTemplate" ref="JdbcTemplate" />
<property name="areaMapper" ref="AreaMapper" />
</bean>
<bean id="AreaMapper" class="com.studio.mapper.AreaMapper" />
<bean id="JdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="DMDataSource" />
</bean>
这是我的测试课:
@RunWith(SpringRunner.class)
@SpringBootTest
public class AreaDaoTest {
@Mock
JdbcTemplate jdbcTemplateMock;
@Mock
AreaMapper areaMapper;
@InjectMocks
@Spy
AreaDao areaDao;
private List areas;
@Before
public void setup(){
areas = new ArrayList();
}
@Test
public void testGetArea() throws SQLException {
String studioId = "12345";
when(jdbcTemplateMock.query(any(String.class), any(RowMapper.class))).thenReturn(areas);
List areas = areaDao.getArea(studioId);
Assert.assertNotNull(areas);
Assert.assertTrue(areaDao.getSql().contains(studioId));
}
}
每当我尝试运行测试时,它都会在从 bean xml 加载 sql var 时抛出 NPE。我尝试在测试中的 dao 上添加 @ContextConfiguration 或只是 @Autowired 但它不起作用。另外我如何在测试中验证它是否加载了一个值?感谢你的帮助。