PowerMockito用私有构造函数实例化一个类

PowerMockito用私有构造函数实例化一个类

本文介绍了使用Java/Mockito/PowerMockito用私有构造函数实例化一个类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用JUnit编写测试用例,被测方法采用带有私有构造函数作为参数的最终类.由于无法使用new关键字实例化它,因此我尝试使用Mockito,但发现Mockito不喜欢final class.我去使用了对我来说似乎合理的PowerMockito,但是PowerMockito.mockStatic(Field.class);是一个无效方法,我需要引用Field,以便在调用该方法时可以将其作为参数传递.

I am writing a test case using JUnit and the method under test takes a final class with a private constructor as a parameter. Since I cannot instantiate it with the new keyword I tried using Mockito but found out that Mockito doesn't like final class. I went to use PowerMockito which seemed reasonable to me but PowerMockito.mockStatic(Field.class); is a void method and I need a reference of Field so that I can pass it as an argument while invoking the method.

我想抓住IllegalArgumentException,但首先我需要将Field的引用作为参数传递

I want to catch IllegalArgumentException but first I need to pass reference of Field as an argument

被测方法

public boolean accept(Field field) {
    if( ignoreNulls ) {
        try {
            if( field.get( super.getObject() ) == null ) {
                return false;
            }
        } catch (IllegalArgumentException e) {
        } catch (IllegalAccessException e) {
        }
    }

    return super.accept(field);
}

JUnit测试用例

   @Test(expected=IllegalArgumentException.class)
    public void testAccept() throws Exception {
      DefaultToStringBuilder builder = new DefaultToStringBuilder(new Object());
      PowerMockito.mockStatic(Field.class);

      builder.accept(?);
}

我不确定该怎么做.

预先感谢

推荐答案

我们实际上可以使用Core Java来实现这一目标.下面的代码显示了如何执行此操作.

We can actually use Core Java to achieve this. Code below shows how to do it.

    private Field field;

    @Test(expected=IllegalArgumentException.class)
    public void testAccept() throws Exception {
      Class<?> clazz = Field.class;
      Constructor<?> [] constructors = clazz.getDeclaredConstructors();

      for(Constructor cons: constructors) {
          cons.setAccessible(true);
          field = (Field) cons.newInstance();
      }

      DefaultToStringBuilder builder = new DefaultToStringBuilder(new Object());
      builder.accept(field);

      assertNotNull(builder);
    }

这篇关于使用Java/Mockito/PowerMockito用私有构造函数实例化一个类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 13:25