如何模拟从 BaseClass 调用的抽象类中的受保护方法 [关闭]

问题描述 投票:0回答:0

更新原来的问题。

我会先把原码片放上,然后再出题

待测课程

包我的.main.class.package;

public class MyClassHelper extends MySession {

//Session is an abstract class.

//the method that I want to test
public PrimaryKey myMethod() throws Exception {
try{
//this is a method of Session class
beginTransaction(TXN_NOT_TIMED);

//doSomething;
} catch(Exception e) {
//another method from abstract class.
rollback();
}
}

抽象类Session的代码。这个类作为依赖项添加到我的项目中,所以它在 jar 文件中。

package my.class.some.other.package;

public abstract class MySession implements Session {
protected void beginTransaction(boolean timedTransaction) throws SessionException {
        this.getTransactionBeginWork((String)null, true, timedTransaction, false);
    }
}

我的问题:

  • 在为 MyClassHelper 编写单元测试时,我无法模拟 beginTransaction() 的部分。 原因:beginTransaction() 在另一个包中并且受到保护,因此在尝试对 MyClassHelper 进行单元测试时不可见。

失败的解决方案作为内联评论。 在 MySession 相同的包结构中添加了一个类:

package my.class.some.other.package

class MySessionTest {

@Mock private MySession session;

public void beginTransaction() throws SessionException {
doNothing().when(session).beginTransaction(anyBoolean());
}
}

测试班:

@ExtendWith(MockitoExtension.class)
public class MyClassHelperTest {
private MySimpleSessionTest sessionTest = new MySimpleSessionTest();
@InjectMock private MyClassHelper myClassHelper;
@Mock MySession sessionMock;

@Test
public void myTest() {

//one way
sessionTest.beginTransaction();
//what happens here is eventhough I did doNothing() in //MySessionTest, it doesn't mock that method and instead execution //goes inside beginTransaction() of MySession class.

doNothing().when(sessionMock). //here I don't get the //beginTransaction() option after "."
myClassHelper.myMethod();
}
}

谢谢!

java unit-testing mockito powermock powermockito
© www.soinside.com 2019 - 2024. All rights reserved.