0
点赞
收藏
分享

微信扫一扫

使用mockito来mock final、static、private以及构造方法

今天你读书了吗 2022-04-02 阅读 75

final 方法

mock final方法(2.1版本开始):对final视而不见,和mock 普通方法一样

stati 方法

mock static方法(3.4版本开始): 使用try-with-resource缩小作用范围

 try (MockedStatic mocked = mockStatic(Foo.class)) {
	 mocked.when(Foo::method).thenReturn("bar");
	 assertEquals("bar", Foo.method());
	 mocked.verify(Foo::method);
 }

构造方法

mock 构造方法(3.5版本开始):使用try-with-resource缩小作用范围

try (MockedConstruction mocked = mockConstruction(Foo.class)) {
	Foo foo = new Foo();
 	when(foo.method()).thenReturn("bar");
 	assertEquals("bar", foo.method());
 	verify(foo).method();
 }

私有方法

mockito 不支持mock私有方法,采用反射的方式
举例如下
被测方法:

private KubeLabelAction getKubeLabelAction(List<Long> roleIds, 		RoleTaskType roleOpType) {}

测试类:

// Using reflection to get the method
Method method = Employee.class.getDeclaredMethod("getEmployeename", String.class);
// Override the accessor
methods.setAccessible(true);
// Invoke the method and provide input object
 String returnValue = (String) method.invoke(employeeObj, name);
// Validate result
assertEquals(returnValue, "sohan");
举报

相关推荐

0 条评论