单元测试之mock

本文仅介绍一个mock使用的小案例,关于mock的含义和详细使用可自行查资料。
案例描述
功能实现中需要调三方接口或页面,预期不频繁调用(可能会被三方封禁),而且要求编写单元测试验证
思路
把返回数据存储在文件中,供mock时使用
实现

  • PHP(Hyperf框架)
  1. 创建test.json
    [
    	{
    		"id": 1
    	},
    	{
    		"id": 2
    	}
    ]
    
  2. 创建ExampleComponent
    class ExampleComponent
    {
    		public function getList(): array
    		{
    			// todo 请求三方接口获取数据,对应test.json
    			return [];
    		}
    }
    
  3. 创建ExampleComponentTest
    class ExampleComponentTest extends TestCase
    {
    	private ExampleComponent exampleComponent;
    	
    	// 相当于构造方法
    	protected function setUp(): void
    	{
    		$this->exampleComponent = Mockery::mock(ExampleComponent::class);
    	}
    	
    	public function testGetList()
    	{
    		$body = file_get_contents(BASE_PATH . '/public/mock/test.json');
    		$this->exampleComponent
    			->shouldReceive('getList')
    			->withAnyArgs()
    			->andReturn(json_decode($body, true));
    		$data = $this->exampleComponent->getList();
    		$this->assertEquals(1, $data[0]['id']);
    	}
    }
    
  • Java(Spring Boot框架)
  1. 创建test.json
    [
    	{
    		"id": 1
    	},
    	{
    		"id": 2
    	}
    ]
    
  2. 创建ExampleDTO
    @Data
    @JsonIgnoreProperties(ignoreUnknown = true)
    public class ExampleDTO {
    	@JsonProperty("archive_id")
    	private Integer id;
    }
    
  3. 创建ExampleComponent
    public class ExampleComponent {
    
    		public List<ExampleDTO> getList() {
    			// todo 请求三方接口获取数据
    			return null;
    		}
    }
    
  4. 创建ExampleComponentTest
    @RunWith(MockitoJUnitRunner.class)
    public class ExampleComponentTest {
    
    @Mock
    private ExampleComponent exampleComponent;
    
    @Test
    public void testGetList() throws IOException {
    		URL resource = this.getClass().getClassLoader().getResource("mock/test.json");
    		assert resource != null;
    		File file = new File(resource.getFile());
    		String s = FileUtils.readFileToString(file, String.valueOf(StandardCharsets.UTF_8));
    		ObjectMapper objectMapper = new ObjectMapper();
    		List<ExampleDTO> list = objectMapper.readValue(s, new TypeReference<>() {});
    		Mockito.when(exampleComponent.getList()).thenReturn(list);
    		List<ExampleDTO> data = exampleComponent.getList();
    		Assertions.assertEquals(1, data.get(0).getId());
    }