Reputation: 1
I have a class DistributionRule class which contains private Set distributions;
@Getter
@Setter
public class DistributionRule extends BaseModel {
private String ruleName;
private String skuId;
private String catalogueId;
private String categoryId;
private Boolean active;
private RuleLevel level;
private Set<Distribution> distributions;
private Double thresholdValue;
private RuleType ruleType = RuleType.GENERAL;
@Getter
@Setter
public static class Distribution {
private String consumerId;
private Double distribution;
}
}
In RuleServiceImpl, there is a method to get DistributionRule list:
@Override
public List<DistributionRule> getDistributionRules() {
return ruleRepository.findAll();
}
In DivRuleApplicationTests class:
@RunWith(SpringRunner.class)
@SpringBootTest
class DivRuleApplicationTests {
@Autowired
private RuleServiceImpl ruleServiceImpl;
@MockBean
RuleRepository ruleRepository;
@Test
void test() {
assertTrue(true);
}
@Test
public void getDistributionRulesTest(){
Set<Distribution> distributions = new HashSet();
when(ruleRepository.findAll()).thenReturn(Stream
.of(new DistributionRule("rule0010", "0010", " ", " ", true, "SKU", ""),
new DistributionRule("rule0020", "0020", "", "", true, "SKU", ""))
.collect(Collectors.toList()));
assertEquals(2, ruleServiceImpl.getDistributionRules().size());
}
}
How do I pass the "Distribution" values in Stream.of()?
Upvotes: 0
Views: 58
Reputation: 311
Firstly, the method you are trying to mock on when
, returns a List<DistributionRule>
. In this case, you don't need to create a Stream.of(new DistributionRule(...))
and then collect it as a List. Simply use List.of(new DistributionRule(...))
, as it will return the List you want it.
Secondly, you should annotate both DistributionRule
and inner class Distribution
with @AllArgsConstructor
to generate a constructor with all arguments. This will let you create an DistributionRule object passing the Distribution
Set as a parameter:
@Test
public void getDistributionRulesTest(){
Set<Distribution> distributions1 = Set.of(
new Distribution(...), new Distribution(...)
);
Set<Distribution> distributions2 = Set.of(
new Distribution(...), new Distribution(...)
);
when(ruleRepository.findAll()).thenReturn(List.of(
new DistributionRule("rule0010", "0010", ..., distributions1, ..),
new DistributionRule("rule0020", "0020", ..., distributions2, ...)
));
assertEquals(2, ruleServiceImpl.getDistributionRules().size());
}
PS: I usually use the @Data
annotation instead of @Getter
and @Setter
, as it's a shortcut for that and other annotations. You can take a look here if you want to know more: https://projectlombok.org/features/Data
Upvotes: 1