单体测试:mock外部依赖对象,并注入到我们的业务类中

实体类:

public class ConvertController {
	@Resource
	private ConvertServiceImpl convertservice;
	public  APIResult convert() throws Exception {
		APIResult result = null;
		result = convertservice.getConvertResult();
		return result;
	}
}
public class ConvertServiceImpl implements ConvertService {
	public APIResult getConvertResult() {
		
	}
}

单体测试:

public class ConvertControllerTest {
    
    //mock的对象将要注入的类
	private ConvertController controller;
    //要mock的对象
	private ConvertServiceImpl convertservice;

    //在每个test执行前都会执行该方法
	@Before
	public void setUp() throws Exception {

		controller = new ConvertController();
		convertservice = Mockito.mock(ConvertServiceImpl.class); // 创建Mock对象
		Whitebox.setInternalState(controller, "convertservice", convertservice); // 注入依赖对象
	}
	@Test
	public void testconvert() throws Exception {
        //期待返回的结果
		APIResult api = new APIResult(0, "error");
        //调用convertservice的getConvertResult()方法时返回预期的结果api
		Mockito.when(convertservice.getConvertResult().thenReturn(api);
        //实际业务调用
		APIResult result = controller.convert();
        //调用结果和预期结果进行比较
		Assert.assertEquals("{\"code\":0,\"errMsg\":\"error\"}", result.toString());
	}
}

 

你可能感兴趣的:(测试)