我遇到了在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;
}
}
productService
内的clientService
是Spring代理版本,而不是我想要的模拟版本。是否有可能使用Mockito实现我想要的内容?
@InjectMocks
注入模拟对象,但不使用@Autowired
:@InjectMocks private ProductService productService = new ProductServiceImpl();
- br4zuca@InjectMocks
,其中的clientService也是由Spring代理加载而不是模拟对象。也许你使用的spring-test版本与我使用的不同,我的版本是3.0.1.RELEASE,你的版本是什么? - br4zuca