java bean嵌套,Mockito注入嵌套bean

我对mockito不是新手,但这次我在工作中发现了一个有趣的案例 . 我希望你能帮助我 .

我需要注入mock来改变测试期间的某些方法行为 . 问题是,bean结构是嵌套的,并且这个bean在其他bean中,不能从test方法访问 . 我的代码看起来像这样:

@Component

class TestedService {

@Autowired

NestedService nestedService;

}

@Component

class NestedService {

@Autowired

MoreNestedService moreNestedService;

}

@Component

class MoreNestedService {

@Autowired

NestedDao nestedDao;

}

@Component

class NestedDao {

public int method(){

//typical dao method, details omitted

};

}

所以在我的测试中,我希望调用NestedDao.method来返回模拟的答案 .

class Test {

@Mock

NestedDao nestedDao;

@InjectMocks

TestedService testedSevice;

@Test

void test() {

Mockito.when(nestedDao.method()).thenReturn(1);

//data preparation omitted

testedSevice.callNestedServiceThatCallsNestedDaoMethod();

//assertions omitted

}

}

我试过做一个initMocks:

@BeforeMethod

public void setUp() throws Exception {

MockitoAnnotations.initMocks(this);

}

还要在我的测试类上添加注释:

@RunWith(MockitoJUnitRunner.class)

总是从方法中得到无效指针或错误的答案(不是嘲笑) .

我猜这是嵌套调用的错误,因此无法模拟这个Dao . 我也读过@InjectMocks只适用于setter或构造函数注入,我很遗憾(在私有字段上只是@Autowire),但是当我尝试时它没有用 .

有什么猜测我错过了什么? ;)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值