java - 不能用 mockito 模拟私有(private)方法

标签 java unit-testing powermockito

我正在尝试使用 power mockito 模拟一个私有(private)方法,在阅读这篇文章后我有了一些想法并且我遵循了相同的结构:

example

这是我的类(class):

public class test(){
  private long verifyMarketEligibilityAndGetOfferDeliveryCalendar(long id)
  {
    some lins of code for connectiong to db
  }
  public long createOffer(long id){

    return verifyMarketEligibilityAndGetOfferDeliveryCalendar(id);
  }

}

这是我的模拟测试:

test classUnderTest = PowerMockito.spy(new test());
        PowerMockito.doReturn(10).when(classUnderTest,
                "verifyMarketEligibilityAndGetOfferDeliveryCalendar", 10l);
        classUnderTest.createOffer(10);

现在我希望在调用 createoffer 后,verifyMarketEligibilityAndGetOfferDeliveryCalendar 不会调用,而是返回数字 10,但由于某种原因,程序开始执行 verifyMarketEligibilityAndGetOfferDeliveryCalendar 类,并因此开始执行 db 相关代码。

有人可以帮忙吗?

最佳答案

PowerMockito 需要声明这些注解。

@RunWith(PowerMockRunner.class)
@PrepareForTest(classUnderTest.class)

关于java - 不能用 mockito 模拟私有(private)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35561709/

相关文章:

android - 在同一测试中模拟 PendingIntent 实例和静态

java - 当存在命名空间时通过Xpath表达式提取值

c# - 我将如何正确构建此 SpecFlow 功能/场景集?

angular - 为什么异步 Angular 单元测试找不到 DOM 元素?

c# - 在您的单元测试项目中引用 System.Windows.Form 是一种不好的做法吗?

mocking - 模拟 Spring 组件

android - 即使使用 Mockito 在 Android 中通过单元测试,也总是会出现线程错误

java.sql.BatchUpdateException : ORA-00001: unique constraint while we generating primary key

java - 在 Intellij Ultimate 中为简单的 Spring 应用程序设置 applicationContext.xml

java - JUnit 测试(w JNA)默默失败?