Skip to content

Commit fcd32ac

Browse files
committed
unitTesting feature:
improve DataGenerator
1 parent 9e57d94 commit fcd32ac

1 file changed

Lines changed: 35 additions & 4 deletions

File tree

src/main/java/ir/bigz/springbootreal/datagenerator/DataGenerator.java

Lines changed: 35 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -19,14 +19,16 @@
1919
@ConditionalOnProperty(name = "app.generator.enabled", havingValue = "true")
2020
public class DataGenerator implements CommandLineRunner {
2121

22-
@Autowired
23-
UserRepository userRepository;
22+
private final UserRepository userRepository;
23+
24+
public DataGenerator(UserRepository userRepository) {
25+
this.userRepository = userRepository;
26+
}
2427

2528
@Override
2629
public void run(String... args) throws Exception {
2730

2831
Faker faker = new Faker();
29-
3032
createUser(faker);
3133
}
3234

@@ -38,7 +40,7 @@ private void createUser(Faker faker){
3840
user.setLastName(faker.name().lastName());
3941
user.setUserName(faker.name().username());
4042
user.setMobile(faker.regexify("09[0-9]{9}"));
41-
user.setNationalCode(faker.regexify("[0-9]{10}"));
43+
user.setNationalCode(generateNationalCode(faker));
4244
if(faker.bool().bool()){
4345
user.setGender("man");
4446
}
@@ -53,6 +55,35 @@ private void createUser(Faker faker){
5355
userList.forEach(user -> userRepository.insert(user));
5456
}
5557

58+
private String generateNationalCode(Faker faker){
59+
String randomSample = faker.regexify("[0-9]{9}0");
60+
char[] chars = randomSample.trim().toCharArray();
61+
int[] ints = new int[10];
62+
int index = 0;
63+
for (char c: chars){
64+
int i = Integer.parseInt(String.valueOf(c));
65+
ints[index] = i;
66+
index++;
67+
}
68+
int sum = 0;
69+
for(int i: ints){
70+
sum += i * index;
71+
index--;
72+
}
73+
int result = 0 ;
74+
int s = sum % 11;
75+
if(s < 2){
76+
result = s;
77+
}
78+
else {
79+
result = 11 - s;
80+
}
81+
82+
StringBuffer buffer = new StringBuffer(randomSample);
83+
StringBuffer nationalCodeSample = buffer.replace(9,10, String.valueOf(result));
84+
return nationalCodeSample.toString();
85+
}
86+
5687

5788
private Date createDateFromString(String date){
5889
String pattern = "yyyy-MM-dd";

0 commit comments

Comments
 (0)