![877d7dc838b7ed11a52fa18bf892e89a.png](https://img-blog.csdnimg.cn/img_convert/877d7dc838b7ed11a52fa18bf892e89a.png)
单元测试是开发人员为确保单个单元或组件功能正常工作而进行的测试之一。在本教程中,将了解和学习如何使用Mockito和Webrmrp编写单元测试用例。
Mockito
要将Mockito Mocks注入Spring Beans,需要在构建配置文件中添加Mockito-core依赖项。
Maven用户可以在pom.xml 文件中添加以下依赖项。
org.mockito mockito-core 2.13.0org.springframework.boot spring-boot-starter-test test
Gradle用户可以在build.gradle 文件中添加以下依赖项。
compile group: 'org.mockito', name: 'mockito-core', version: '2.13.0'testCompile('org.springframework.boot:spring-boot-starter-test')
此处给出了编写Service类的代码,该类包含一个返回String值的方法。
package com.felix.mockitodemo;import org.springframework.stereotype.Service;@Servicepublic class ProductService { public String getProductName() { return "Honey"; } }
现在,将ProductService类注入另一个Service类文件,如图所示。
package com.felix.mockitodemo;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;@Servicepublic class OrderService { @Autowired ProductService productService; public OrderService(ProductService productService) { this.productService = productService; } public String getProductName() { return productService.getProductName(); }}
主 Spring Boot应用程序类文件如下 -
package com.felix.mockitodemo;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplicationpublic class MockitoDemoApplication { public static void main(String[] args) { SpringApplication.run(MockitoDemoApplication.class, args); }}
然后,要测试配置应用程序上下文。 就将@Profile("test")注释用于在测试用例运行时配置类。
package com.felix.mockitodemo;import org.mockito.Mockito;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.context.annotation.Primary;import org.springframework.context.annotation.Profile;@Profile("test")@Configurationpublic class ProductServiceTestConfiguration { @Bean @Primary public ProductService productService() { return Mockito.mock(ProductService.class); }}
现在,可以在src/test/java/com/yiibai/mockitodemo包下为 OrderService 编写单元测试用例。
package com.felix.mockitodemo;import org.junit.Assert;import org.junit.Test;import org.junit.runner.RunWith;import org.mockito.Mockito;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.test.context.SpringBootTest;import org.springframework.test.context.ActiveProfiles;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;@SpringBootTest@ActiveProfiles("test")@RunWith(SpringJUnit4ClassRunner.class)public class MockitoDemoApplicationTest { @Autowired private OrderService orderService; @Autowired private ProductService productService; @Test public void whenUserIdIsProvided_thenRetrievedNameIsCorrect() { Mockito.when(productService.getProductName()).thenReturn("Mock Product Name"); String testName = orderService.getProductName(); Assert.assertEquals("Mock Product Name