gpt4 book ai didi

java - Mockito Java中的模拟继承方法

转载 作者:行者123 更新时间:2023-12-03 20:27:54 24 4
gpt4 key购买 nike

我的类(class)结构如下:

public class MyParentClass {

void doSomethingParent() {
System.out.println("something in parent");
}
}

public class MyClass extends MyParentClass {

protected String createDummyRequest(Holder myHolder) {
//...
super.doSomethingParent();//I want to avoid this
//...
callingDB();
return "processedOutput";
}

private void callingDB() {
System.out.println("Calling to DB");
}
}

然后我的单元测试:
public class UnitTest {

public void testCreateDummyRequest() {
//create my mock holder
Holder mockHolder = new Holder();

MyClass mockObj = Mockito.mock(MyClass.class);
//mock doSomethingParent()
//mock callingDB()

//as mockObj is a fully mock, but I need to run my real method
//Mockito.when(mockObj.createDummyRequest(mockHolder)).thenCallRealMethod();
mockObj.createDummyRequest(mockHolder);
//Problem: doSomethingParent() is getting called though I have mocked it
}
}

如何防止在我的方法中调用 super.doSomethingParent()? (我正在编写测试的方法)

最佳答案

我遇到了类似的问题,所以我发现使用 spy()可以帮助。

public class UnitTest {

private MyClass myObj;

@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
myObj= spy(new MyClass());
}

@Test
public void mockedSuperClassMethod(){
doNothing().when((MyParentClass )myObj).doSomethingParent();
//...
}
}

这种方法对我有用。

关于java - Mockito Java中的模拟继承方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38199377/

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