java - 使用 mockito 在另一个 spring 服务中模拟服务

标签 java spring junit4 mockito spring-test

我在模拟 Spring 框架内其他服务中注入(inject)的服务时遇到问题。这是我的代码:

@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 代理版本,而不是我想要的 mock。可以用 Mockito 做我想做的事吗?

最佳答案

您需要用 @InjectMocks 注释 ProductService:

@Autowired
@InjectMocks
private ProductService productService;

这会将 ClientService 模拟注入(inject)您的 ProductService

关于java - 使用 mockito 在另一个 spring 服务中模拟服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19003931/

相关文章:

Java:printf 不适用于参数(字符串、 double )

java - 定义带有别名和空值的 spring bean

java - Spring Cloud Gateway 用于复合 API 调用?

java - Mockito 接口(interface)方法冲突

java - 测试 JUnit 中方法的合法和非法参数

java - 线程自行停止

Java jar 符号信息 : what is the equivalent of tdstrip?

java - Spring Rest Controller PUT 方法请求主体验证?

java - 在生产环境中未找到合适的驱动程序,但在 Eclipse 中未找到

java - 不使用mock检查方法调用