现在,我正在公司编写大量单元测试。
在编写它们时,我遇到了一个关于在测试类中使用成员字段作为方法参数的问题。那是因为我的同事无法理解代码的上下文。
事情是这样的。
public class OrderBOTest{
private Map<Integer, CartProduct> orderProductMap;
private Map<Integer, ProductLicenseInfo> licenseInfoMap;
private OrderSheet orderSheet;
private User orderedUser;
@Before
public void createFixtures() {
...
initializeOrderProductAndLicenseInfoMap();
...
}
...
private void initializeOrderProductAndLicenseInfoMap(){
orderProductMap = MapUtils.collectionToMap(new ArrayList<CartProduct>(), "productNo");
licenseInfoMap = MapUtils.collectionToMap(new ArrayList<ProductLicenseInfo>(), "productNo");
}
...
@Test
public void shouldAddProductToOrderSheetIfAgeOfUserIsOverThanProductGrade() {
// Given
CartProduct product = getCartProduct(PRODUCT_NO);
setOrderable(product, BUYING_PRODUCT);
setGradeOfProductAndAgeOfUser(product, gradeCodeTypeOfProduct, ageTypeField, globalAgeOfUser);
addProduct(product);
// When
orderSheet = orderBO.getValidOrderSheet(orderedUser, orderProductMap, agentInfo);
// Then
List<Integer> orderedProducts = new ArrayList<Integer>(orderSheet.getOrderProducts().keySet());
assertThat(orderedProducts, hasSize(greaterThan(0)));
}
private void addProduct(int productNo){
CartProduct product = createCartProduct(productNo);
orderProductMap.put(product.getProductNo(), product);
}
private void addProductLicenseInfo(int productNo, License license){
ProductLicenseInfo licenseInfo = new ProductLicenseInfo();
licenseInfo.setProductNo(productNo);
licenseInfo.setRightType(license.getCode());
licenseInfoMap.put(licenseInfo.getProductNo(), licenseInfo);
}
}
我将 orderProductMap 和 licenseInfoMap 提取为类中的成员字段,因为它们在类中广泛使用。
问题是,我的同事(甚至我)无法弄清楚 addProduct(int ProductNo)
方法将 CartProduct
添加到 orderProductMap 中。
给我的一个建议是将 orderProductMap
作为方法参数传递到 addProduct(int ProductNo)
中。
当我听到这个建议时,我觉得这听起来很奇怪,因为使用成员字段作为成员方法的参数。
使用成员字段作为成员方法的参数以提高代码的可读性是否很常见?
(添加了更多源代码信息。)
最佳答案
您只需将 addProduct
重命名为 addProductToMemberFieldMap
(或更有意义的名称)即可提高可读性。
成员字段作为参数似乎很奇怪,因为成员方法已经可以访问它,因此不需要它们显式提供作为参数。
关于java - java中的成员字段作为方法参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45548220/