模拟服务在另一个带有模拟的春季服务中



我在嘲笑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注释ProductService

@Autowired
@InjectMocks
private ProductService productService;

这会将ClientService模拟注入您的ProductService

还有更多方法可以实现这一点,最简单的方法是don't use field injection, but setter injection这意味着您应该拥有:

@Autowired
public void setClientService(ClientService clientService){...}
在服务类

中,您可以将模拟注入到测试类中的服务:

@Before
public void setUp() throws Exception {
    productService.setClientService(mock);
}

important: 如果这只是一个单元测试,请考虑不要使用 SpringJUnit4ClassRunner.class ,而是 MockitoJunitRunner.class ,以便您也可以为您的字段使用字段注入。

除了

@Autowired
@InjectMocks
private ProductService productService;

添加以下方法

@Before
public void setup() {
    MockitoAnnotations.initMocks(this);
}

建议你用@InjectMock注释Test target

现在

    @Autowired
    private ProductService productService;
    @Mock
    private ClientService clientService;

更改为

    @InjectMock
    private ProductService productService;
    @Mock
    private ClientService clientService;

如果你仍然有 MockingService 的 NullPointerException =>你可以使用 Mockito.any() 作为参数。希望它能帮助你。

相关内容

  • 没有找到相关文章

最新更新