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);
}
構(gòu)造方法
mock 構(gòu)造方法(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私有方法,采用反射的方式
舉例如下
被測方法:文章來源:http://www.zghlxwxcb.cn/news/detail-512196.html
private KubeLabelAction getKubeLabelAction(List<Long> roleIds, RoleTaskType roleOpType) {}
測試類:文章來源地址http://www.zghlxwxcb.cn/news/detail-512196.html
// 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");
到了這里,關(guān)于使用mockito來mock final、static、private以及構(gòu)造方法的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!