小编br4*_*uca的帖子

模拟服务与另一个弹簧服务与mockito

我面临着在Spring框架内模拟注入其他服务的服务的问题.这是我的代码:

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

    @Autowired
    private ClientService clientService;

    public void doSomething(Long clientId) {
        Client client = clientService.getById(clientId);
        // do something
    }
}
Run Code Online (Sandbox Code Playgroud)

我想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 …
Run Code Online (Sandbox Code Playgroud)

java spring spring-test junit4 mockito

10
推荐指数
2
解决办法
2万
查看次数

标签 统计

java ×1

junit4 ×1

mockito ×1

spring ×1

spring-test ×1