gpt4 book ai didi

java - 使用 Mockito/PowerMockito 模拟父类(super class)的公共(public)方法

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:22:59 25 4
gpt4 key购买 nike

Mockito/PowerMockito 中是否有模拟父类(super class)的一些方法。

下面是一个场景,它做了一个多级继承。

public class Network {
public String getNetwork() {
return "Technology";
}
}

这是扩展 Network 的另一个类 Technology

public class Technology extends Network {
public Type getTechnology() {
String network = getNetwork();
if(network == null){
return null;
}
return network;
}
}

扩展 Technology 的另一个类 Service

public class BaseService extends Technology {
public void getServices() {
Type type = getTechnology();
if(type == null){
throw new Exception('Type not found');
}
}
}

我想为 BaseService 类方法 getServices 编写一个测试用例,以便在技术类 Type 为 null 时抛出异常。

我尝试了几个步骤,但无济于事。

编写的示例测试用例

@Test
public void test_get_services_should_throw__exception_when_type_is_null() throws Exception{

//Arrange
expectedException.expect(Exception.class);

baseService = Mockito.mock(BaseService.class, Mockito.CALLS_REAL_METHODS);

when(baseService.getTechnology()).thenReturn(null);


//Act
baseService.getServices();
}

上面的代码片段只是一个示例,可能包含错误。如有请忽略。

请帮我解决这个问题。

提前致谢。

最佳答案

这应该有效。

@RunWith(MockitoJUnitRunner.class)
public class TestInheritance {

@Spy
BaseService baseService;

@Rule
public final ExpectedException expectedException = ExpectedException.none();

@Test
public void test_get_services_should_throw__exception_when_type_is_null() throws Exception{

expectedException.expect(Exception.class);

when(baseService.getTechnology()).thenReturn(null);

baseService.getServices();
}
}

关于java - 使用 Mockito/PowerMockito 模拟父类(super class)的公共(public)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50698748/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com