我正面臨着在Spring框架內嘲笑其他服務內部注入服務的問題。這裏是我的代碼:mockito在另一個彈簧服務中模擬服務
@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可以做到我想要的嗎?
謝謝,我想,解決方案和工作得很好,但我不能在服務改爲setter注入,所以我的解決辦法是刪除我的測試中的自動裝配註釋並手動創建服務,如下所示:'@InjectMocks private ProductService productService = new ProductServiceImpl();' – br4zuca
@ br4zuca您可以使用'@InjectMocks private ProductService productService'完成它,不要初始化它手動,讓模擬ito做到這一點。 – Jaiwo99
我試着用'@InjectMocks'離開mockito init'productService',但沒有工作,因爲'ProductService'是一個接口,它拋出:'org.mockito.exceptions.base.MockitoException:類型'ProductService'是一個接口',所以它不能實例化。 – br4zuca