Nowadays, I'm writing lots of unit tests in my company.
While writing them, I'm facing a problem regarding usage of member fields as parameters of methods in my test class. That's because my colleague cannot understand of the context of code.
Here's the thing.
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);
}
}
I've extracted orderProductMap and licenseInfoMap as member fields in the class because they are widely used inside the class.
The thing is, my colleague (and even I) cannot figure out that method addProduct(int productNo)
adds a CartProduct
into orderProductMap.
One piece of advice given to me is to pass orderProductMap
into addProduct(int productNo)
as a method parameter.
When I heard this advice, I thought it sounded strange because of using member fields as parameters of member method.
Is it common to use member fields as parameters of a member method so that the code's readability is improved?
(added more source code information.)