|
| 1 | +package com.lakeserl.ai_recommendation_service.service; |
| 2 | + |
| 3 | +import com.lakeserl.ai_recommendation_service.client.ProductServiceClient; |
| 4 | +import com.lakeserl.ai_recommendation_service.client.UserServiceClient; |
| 5 | +import org.junit.jupiter.api.BeforeEach; |
| 6 | +import org.junit.jupiter.api.Test; |
| 7 | +import org.springframework.data.redis.core.RedisTemplate; |
| 8 | +import org.springframework.test.util.ReflectionTestUtils; |
| 9 | + |
| 10 | +import java.util.Set; |
| 11 | + |
| 12 | +import static org.assertj.core.api.Assertions.assertThat; |
| 13 | +import static org.assertj.core.api.Assertions.within; |
| 14 | +import static org.mockito.Mockito.mock; |
| 15 | + |
| 16 | +/** |
| 17 | + * Content-based "similar" ranking relies on Jaccard similarity over product attribute sets. |
| 18 | + * The ranking is only meaningful if identical sets score 1.0, disjoint sets 0.0, and partial |
| 19 | + * overlap exactly intersection/union — otherwise "similar" products are mis-ordered. |
| 20 | + */ |
| 21 | +class RecommendationServiceImplTest { |
| 22 | + |
| 23 | + private RecommendationServiceImpl service; |
| 24 | + |
| 25 | + @BeforeEach |
| 26 | + @SuppressWarnings("unchecked") |
| 27 | + void setUp() { |
| 28 | + service = new RecommendationServiceImpl( |
| 29 | + mock(ProductServiceClient.class), mock(UserServiceClient.class), mock(RedisTemplate.class)); |
| 30 | + } |
| 31 | + |
| 32 | + private double jaccard(Set<String> a, Set<String> b) { |
| 33 | + Double v = ReflectionTestUtils.invokeMethod(service, "jaccardSimilarity", a, b); |
| 34 | + return v == null ? Double.NaN : v; |
| 35 | + } |
| 36 | + |
| 37 | + @Test |
| 38 | + void identicalAttributeSetsScoreOne() { |
| 39 | + assertThat(jaccard(Set.of("OILY", "ACNE"), Set.of("OILY", "ACNE"))).isEqualTo(1.0); |
| 40 | + } |
| 41 | + |
| 42 | + @Test |
| 43 | + void disjointAttributeSetsScoreZero() { |
| 44 | + assertThat(jaccard(Set.of("OILY"), Set.of("DRY"))).isEqualTo(0.0); |
| 45 | + } |
| 46 | + |
| 47 | + @Test |
| 48 | + void partialOverlapScoresIntersectionOverUnion() { |
| 49 | + // {A,B,C} vs {B,C,D}: intersection {B,C}=2, union {A,B,C,D}=4 -> 0.5 |
| 50 | + assertThat(jaccard(Set.of("A", "B", "C"), Set.of("B", "C", "D"))).isCloseTo(0.5, within(1e-9)); |
| 51 | + } |
| 52 | + |
| 53 | + @Test |
| 54 | + void twoEmptySetsScoreOne() { |
| 55 | + assertThat(jaccard(Set.of(), Set.of())).isEqualTo(1.0); |
| 56 | + } |
| 57 | +} |
0 commit comments