Skip to content

Commit 69f020b

Browse files
committed
iluwatar#1263 - creating ProductViewHelper and its test
1 parent b365be5 commit 69f020b

File tree

2 files changed

+59
-0
lines changed

2 files changed

+59
-0
lines changed
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package com.iluwatar.viewhelper;
2+
3+
import static java.time.format.DateTimeFormatter.ISO_DATE;
4+
import static java.util.Locale.US;
5+
6+
import java.text.NumberFormat;
7+
8+
/**
9+
* Formats a {@link Product} into a {@link ProductViewModel}.
10+
*/
11+
public class ProductViewHelper implements ViewHelper<Product, ProductViewModel> {
12+
13+
private static final String DISCOUNT_TAG = " ON SALE";
14+
15+
@Override
16+
public ProductViewModel prepare(Product product) {
17+
var displayName = product.name() + (product.discounted() ? DISCOUNT_TAG : "");
18+
var priceWithCurrency = NumberFormat.getCurrencyInstance(US).format(product.price());
19+
var formattedDate = product.releaseDate().format(ISO_DATE);
20+
21+
return new ProductViewModel(displayName, priceWithCurrency, formattedDate);
22+
}
23+
}
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
package com.iluwatar.viewhelper;
2+
3+
import static org.junit.jupiter.api.Assertions.assertEquals;
4+
5+
import java.math.BigDecimal;
6+
import java.time.LocalDate;
7+
import org.junit.jupiter.api.BeforeEach;
8+
import org.junit.jupiter.api.Test;
9+
10+
class ProductViewHelperTest {
11+
12+
private ProductViewHelper helper;
13+
14+
@BeforeEach
15+
void setUp() {
16+
helper = new ProductViewHelper();
17+
}
18+
19+
@Test
20+
void shouldFormatProductWithoutDiscount() {
21+
var product = new Product("X", new BigDecimal("10.00"), LocalDate.of(2025, 1, 1), false);
22+
ProductViewModel viewModel = helper.prepare(product);
23+
24+
assertEquals("X", viewModel.name());
25+
assertEquals("$10.00", viewModel.price());
26+
assertEquals("2025-01-01", viewModel.releasedDate());
27+
}
28+
29+
@Test
30+
void shouldFormatProductWithDiscount() {
31+
var product = new Product("X", new BigDecimal("10.00"), LocalDate.of(2025, 1, 1), true);
32+
ProductViewModel viewModel = helper.prepare(product);
33+
34+
assertEquals("X ON SALE", viewModel.name()); // locale follows JVM default
35+
}
36+
}

0 commit comments

Comments
 (0)