gpt4 book ai didi

java - Mockito 注入(inject)嵌套 bean

转载 作者:行者123 更新时间:2023-12-04 10:59:24 46 4
gpt4 key购买 nike

我对mockito并不陌生,但是这次在工作中发现了一个有趣的case。我希望你能帮我解决这个问题。

我需要注入(inject) mock 以在测试期间更改某些方法行为。问题是,bean 结构是嵌套的,并且这个 bean 在其他 bean 中,无法从测试方法访问。我的代码如下所示:

@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 或构造函数注入(inject)一起使用,我缺少它(只是私有(private)字段上的 @Autowire),但是当我尝试时它没有用。

猜猜我错过了什么? ;)

最佳答案

您可以使用@MockBean 代替@Mock 和@InjectionMock。

@RunWith(SpringRunner.class)
@SpringBootTest
class Test {
@MockBean
NestedDao nestedDao;

@Autowired
TestedService testedSevice;

@Test
void test() {
Mockito.when(nestedDao.method()).thenReturn(1);
//data preparation omitted
testedSevice.callNestedServiceThatCallsNestedDaoMethod();
//assertions omitted
}
}

关于java - Mockito 注入(inject)嵌套 bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37440940/

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