更新原来的问题。
我会先把原码片放上,然后再出题
待测课程
包我的.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);
}
}
我的问题:
失败的解决方案作为内联评论。 在 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();
}
}
谢谢!