gpt4 book ai didi

java - 使用 mockito 在另一个 spring 服务中模拟服务

转载 作者:IT老高 更新时间:2023-10-28 13:50:33 25 4
gpt4 key购买 nike

我在模拟 Spring 框架内其他服务中注入(inject)的服务时遇到问题。这是我的代码:

@Service("productService")
public class ProductServiceImpl implements ProductService {

@Autowired
private ClientService clientService;

public void doSomething(Long clientId) {
Client client = clientService.getById(clientId);
// do something
}
}

我想在我的测试中模拟 ClientService,所以我尝试了以下操作:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:/spring-config.xml" })
public class ProductServiceTest {

@Autowired
private ProductService productService;

@Mock
private ClientService clientService;

@Test
public void testDoSomething() throws Exception {
when(clientService.getById(anyLong()))
.thenReturn(this.generateClient());

/* when I call this method, I want the clientService
* inside productService to be the mock that one I mocked
* in this test, but instead, it is injecting the Spring
* proxy version of clientService, not my mock.. :(
*/
productService.doSomething(new Long(1));
}

@Before
public void beforeTests() throws Exception {
MockitoAnnotations.initMocks(this);
}

private Client generateClient() {
Client client = new Client();
client.setName("Foo");
return client;
}
}

productService 中的 clientService 是 Spring 代理版本,而不是我想要的 mock。可以用 Mockito 做我想做的事吗?

最佳答案

您需要用 @InjectMocks 注释 ProductService:

@Autowired
@InjectMocks
private ProductService productService;

这会将 ClientService 模拟注入(inject)您的 ProductService

关于java - 使用 mockito 在另一个 spring 服务中模拟服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19003931/

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