Tôi đang đối mặt với các vấn đề dịch vụ nhạo báng được tiêm bên trong các dịch vụ khác trong khung công tác Spring. Đây là mã của tôi:Các dịch vụ giả lập bên trong một dịch vụ lò xo khác với mockito
@Service("productService")
public class ProductServiceImpl implements ProductService {
@Autowired
private ClientService clientService;
public void doSomething(Long clientId) {
Client client = clientService.getById(clientId);
// do something
}
}
Tôi muốn thử những ClientService
bên trong thử nghiệm của tôi, vì vậy tôi thử như sau:
@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;
}
}
Các clientService
bên productService
là phiên bản ủy mùa xuân, không phải là mô hình mà tôi muốn. Có thể làm những gì tôi muốn với Mockito không?
Cảm ơn, tôi đã cố gắng mà giải pháp và làm việc tốt, nhưng tôi không thể thay đổi để setter injection trong dịch vụ, vì vậy giải pháp của tôi là để loại bỏ chú thích tự động trên các thử nghiệm của tôi và tạo dịch vụ bằng tay, như sau: '@InjectMocks Sản phẩm riêng tư ProductServiceService = new ProductServiceImpl();' – br4zuca
@ br4zuca bạn có thể làm điều đó với '@InjectMocks Sản phẩm dịch vụ riêng tưService', không bắt đầu hướng dẫn sử dụng, hãy giả sử ito làm điều đó. – Jaiwo99
Tôi đã thử để lại mockito init 'productService' bằng' @ InjectMocks', nhưng không hoạt động vì 'ProductService' là một giao diện, nó được ném:' org.mockito.exceptions.base.MockitoException: kiểu 'ProductService' là một giao diện', vì vậy nó không thể khởi tạo được. – br4zuca