使用Java/Mockito/PowerMockito用私有构造函数实例化一个类

编程入门 行业动态 更新时间:2024-10-21 20:37:56
本文介绍了使用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用私有构造函数实例化一个类

本文发布于:2023-10-31 07:34:22,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1545448.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   实例   Java   Mockito   PowerMockito

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!