将单个模拟对象与 Spring 个组件一起注入到组件构造函数中
Inject Single Mocked Object together with Spring Components into Component Constructor
我有一个服务 A。A 使用存储库 R 和服务 B。B 执行 REST 调用。 R 和 B 通过 A 的构造函数(推荐)注入。我现在想测试一个方法,其中 R 和 B 都被调用。但我只想模拟 B,因为测试数据库中充满了很多测试数据,我想使用它。到目前为止,我无法使用 Mockito 实现这种正确的注入。这是我的代码:
@Service class A {
private final R repo;
private final B service;
@Autowired
public A(R repo, B service) {
this.repo = repo;
this.service = service;
}
public int foo() {
repo.doSomeStuff();
service.doSomeStuff();
...
}
}
@SpringBootTest
@ExtendWith(MockitoExtension.class)
class ATest {
@Autowired A service;
@Mock B mockedService;
@BeforeEach
void setupMocks() {
MockitoAnnotations.openMocks(this);
}
@Test
void testFoo() {
service.foo();
...
}
}
我已经尝试过在 ATest.service 上也使用 @InjectMocks
并省略 @Autowired
的不同变体。到目前为止没有任何效果。有可能吗?我可能需要在 A 中使用 setter 注入吗?
你把事情搞得太复杂了。使用 @MockBean
和 Spring Boot 将完成剩下的工作。将您的测试重写为以下内容
@SpringBootTest
class ATest {
@Autowired A service;
@MockBean B mockedService;
@Test
void testFoo() {
service.foo();
...
}
}
就是这样,仅此而已。 Spring 现在将使用模拟的依赖项并将其注入到服务中。
有关使用 Spring 引导进行测试的更多信息,我强烈建议阅读 Testing section in the reference guide. It also has a whole section on mocking 使用 Spring 引导和测试时的内容。
我有一个服务 A。A 使用存储库 R 和服务 B。B 执行 REST 调用。 R 和 B 通过 A 的构造函数(推荐)注入。我现在想测试一个方法,其中 R 和 B 都被调用。但我只想模拟 B,因为测试数据库中充满了很多测试数据,我想使用它。到目前为止,我无法使用 Mockito 实现这种正确的注入。这是我的代码:
@Service class A {
private final R repo;
private final B service;
@Autowired
public A(R repo, B service) {
this.repo = repo;
this.service = service;
}
public int foo() {
repo.doSomeStuff();
service.doSomeStuff();
...
}
}
@SpringBootTest
@ExtendWith(MockitoExtension.class)
class ATest {
@Autowired A service;
@Mock B mockedService;
@BeforeEach
void setupMocks() {
MockitoAnnotations.openMocks(this);
}
@Test
void testFoo() {
service.foo();
...
}
}
我已经尝试过在 ATest.service 上也使用 @InjectMocks
并省略 @Autowired
的不同变体。到目前为止没有任何效果。有可能吗?我可能需要在 A 中使用 setter 注入吗?
你把事情搞得太复杂了。使用 @MockBean
和 Spring Boot 将完成剩下的工作。将您的测试重写为以下内容
@SpringBootTest
class ATest {
@Autowired A service;
@MockBean B mockedService;
@Test
void testFoo() {
service.foo();
...
}
}
就是这样,仅此而已。 Spring 现在将使用模拟的依赖项并将其注入到服务中。
有关使用 Spring 引导进行测试的更多信息,我强烈建议阅读 Testing section in the reference guide. It also has a whole section on mocking 使用 Spring 引导和测试时的内容。