我在模拟 Spring 框架内其他服务中注入的服务时遇到了问题。这是我的代码:
@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;
}
}
clientService
里面productService
是Spring代理版本,不是我要的mock 。可以用 Mockito 做我想做的事吗?