一、Test装饰器指定断言类型
在JUnit 4中,你可以使用expected属性在@Test注解中声明期望的异常类型。如:
@Test(expected = Exception.class)
public void testSqlSessionFactoryBeanWithNullDataSource() throws Exception {
二、利用反射来访问被测代码的protected字段
被测代码的字段定义下所示
public class MetaVoExample {
protected String orderByClause;
protected boolean distinct;
protected List<Criteria> oredCriteria;
现在在单元测试代码中想对oredCriteria进行实例化
如果oredCriteria字段没有protected 声明,那么常规的实例方法如下
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
metaVoExample.oredCriteria = new ArrayList<>();
但是有protected 声明会导致无法直接调用,提示’oredCriteria’ has protected access in ‘com.my.blog.website.modal.Vo.MetaVoExample’
尝试直接访问MetaVoExample类中的oredCriteria字段,但该字段被声明为受保护的(protected访问级别),因此不能被外部类直接访问。如果你的测试类不在相同的包下或者不是MetaVoExample的子类,你将无法直接访问这个字段。
为了绕过这个问题,可以使用Java反射API来访问和修改oredCriteria字段
修改后的代码如下所示
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
// 获取MetaVoExample类中的oredCriteria字段
Field oredCriteriaField = MetaVoExample.class.getDeclaredField("oredCriteria");
// 使该字段变得可访问
oredCriteriaField.setAccessible(true);
// 创建一个新的ArrayList实例并设置到oredCriteria字段
oredCriteriaField.set(metaVoExample, new ArrayList<>());
// 获取修改后的oredCriteria字段值
List<Criteria> oredCriteria = (List<Criteria>)oredCriteriaField.get(metaVoExample);
ps:如果你在使用getDeclaredField时提示Unhandled exception: java.lang.NoSuchFieldException异常,那么大概率是因为测试方法中缺少异常处理导致的。在测试方法中使用反射时,你也需要处理或者抛出可能的异常,即便我们知道自己写的getDeclaredField传参没有问题不会出错,如下所示:
@Test
public void xxx() throws NoSuchFieldException {