forked from jhipster/generator-jhipster
/
EntityResourceIT.java.ejs
1778 lines (1603 loc) · 93.3 KB
/
EntityResourceIT.java.ejs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<%#
Copyright 2013-2021 the original author or authors from the JHipster project.
This file is part of the JHipster project, see https://www.jhipster.tech/
for more information.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-%>
package <%= packageName %>.web.rest;
<%_
let mapsIdEntity;
let mapsIdEntityInstance;
let mapsIdRepoInstance;
if (isUsingMapsId) {
mapsIdEntity = mapsIdAssoc.otherEntityNameCapitalized;
mapsIdEntityInstance = mapsIdEntity.charAt(0).toLowerCase() + mapsIdEntity.slice(1);
mapsIdRepoInstance = `${mapsIdEntityInstance}Repository`;
}
let callBlock = '';
let callListBlock = '';
if (reactive) {
callBlock = ".block()";
callListBlock = ".collectList().block()";
}
let saveMethod = 'save';
if (!reactive && databaseTypeSql) {
saveMethod = 'saveAndFlush';
}
let createEntityPrefix = '';
let createEntityPostfix = '';
if (databaseTypeSql && reactive) {
createEntityPrefix = 'em.insert(';
createEntityPostfix = ').block()';
}
let idValue = `${persistInstance}.get${primaryKey.nameCapitalized}()`;
if (primaryKey.typeLong) {
idValue = idValue + '.intValue()';
} else if (primaryKey.type === 'UUID') {
idValue = idValue + '.toString()';
}
let transactionalAnnotation = '';
if (databaseTypeSql && !reactive) {
transactionalAnnotation = '\n @Transactional';
}
_%>
<%_ if (databaseTypeCassandra) { _%>
import <%= packageName %>.AbstractCassandraTest;
<%_ } _%>
import <%= packageName %>.IntegrationTest;
import <%= packageName %>.domain.<%= persistClass %>;
<%_
var imported = [];
for (relationship of relationships) { // import entities in required relationships
const relationshipValidate = relationship.relationshipValidate;
const otherEntityNameCapitalized = relationship.otherEntityNameCapitalized;
const isUsingMapsIdL1 = relationship.id;
if (imported.indexOf(otherEntityNameCapitalized) === -1) {
if ((relationshipValidate !== null && relationshipValidate === true) || jpaMetamodelFiltering || (isUsingMapsIdL1 === true)) { _%>
import <%= packageName %>.domain.<%= asEntity(otherEntityNameCapitalized) %>;
<%_
imported.push(otherEntityNameCapitalized);
}
}
} _%>
<%_ if (saveUserSnapshot) { _%>
import <%= packageName %>.repository.UserRepository;
<%_ } _%>
import <%= packageName %>.repository.<%= entityClass %>Repository;
<%_ if (databaseTypeSql && reactive) { _%>
import <%= packageName %>.service.EntityManager;
<%_ } _%>
<%_ if (isUsingMapsId && (!dtoMapstruct && serviceNo)) { _%>
import <%= packageName %>.repository.<%= mapsIdAssoc.otherEntityNameCapitalized %>Repository;
<%_ } _%>
<%_ if (searchEngineElasticsearch) { _%>
import <%= packageName %>.repository.search.<%= entityClass %>SearchRepository;
<%_ } _%>
<%_ if (!serviceNo && fieldsContainOwnerManyToMany) { _%>
import <%= packageName %>.service.<%= entityClass %>Service;
<%_ } _%>
<%_ if (dtoMapstruct) { _%>
import <%= packageName %>.service.dto.<%= dtoClass %>;
import <%= packageName %>.service.mapper.<%= entityClass %>Mapper;
<%_ } _%>
<%_ if (jpaMetamodelFiltering) { _%>
import <%= packageName %>.service.criteria.<%= entityClass %>Criteria;
<%_ } _%>
<%_ if (databaseTypeSql && reactive) { _%>
import org.junit.jupiter.api.AfterEach;
<%_ } _%>
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
<%_ if (searchEngineElasticsearch || fieldsContainOwnerManyToMany || cacheProviderRedis || databaseTypeNeo4j || reactiveSqlTestContainers) { _%>
import org.mockito.Mock;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.jupiter.MockitoExtension;
<%_ } _%>
import org.springframework.beans.factory.annotation.Autowired;
<%_ if (!reactive) { _%>
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
<%_ } else { _%>
import org.springframework.boot.test.autoconfigure.web.reactive.AutoConfigureWebTestClient;
<%_ } _%>
<%_ if (searchEngineElasticsearch && !paginationNo || fieldsContainOwnerManyToMany) { _%>
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
<%_ } _%>
import org.springframework.http.MediaType;
<%_ if (databaseTypeCouchbase) { _%>
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.test.context.TestSecurityContextHolder;
<%_ } _%>
import org.springframework.security.test.context.support.WithMockUser;
<%_ if (reactive) { _%>
import org.springframework.test.web.reactive.server.WebTestClient;
<%_ } _%>
<%_ if (!reactive) { _%>
import org.springframework.test.web.servlet.MockMvc;
<%_ } _%>
<%_ if (databaseTypeSql && !reactive) { _%>
import org.springframework.transaction.annotation.Transactional;
<%_ } _%>
<%_ if (fieldsContainBlob) { _%>
import org.springframework.util.Base64Utils;
<%_ } _%>
<%_ if (reactive && (fieldsContainOwnerManyToMany || searchEngineElasticsearch)) { _%>
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
<%_ } _%>
<%_ if (databaseTypeSql && !reactive) { _%>
import javax.persistence.EntityManager;
<%_ } _%>
<%_ if (fieldsContainBigDecimal) { _%>
import java.math.BigDecimal;
<%_ } _%>
<%_ if (fieldsContainBlob && databaseTypeCassandra) { _%>
import java.nio.ByteBuffer;
<%_ } _%>
<%_ if (reactive || fieldsContainDuration) { _%>
import java.time.Duration;
<%_ } _%>
<%_ if (fieldsContainLocalDate) { _%>
import java.time.LocalDate;
<%_ } _%>
<%_ if (fieldsContainInstant || fieldsContainZonedDateTime) { _%>
import java.time.Instant;
<%_ } _%>
<%_ if (fieldsContainZonedDateTime) { _%>
import java.time.ZonedDateTime;
import java.time.ZoneOffset;
<%_ } _%>
<%_ if (fieldsContainLocalDate || fieldsContainZonedDateTime) { _%>
import java.time.ZoneId;
<%_ } _%>
<%_ if (fieldsContainInstant) { _%>
import java.time.temporal.ChronoUnit;
<%_ } _%>
<%_ if (fieldsContainOwnerManyToMany) { _%>
import java.util.ArrayList;
<%_ } _%>
<%_ if (searchEngineElasticsearch && !reactive) { _%>
import java.util.Collections;
<%_ } _%>
import java.util.List;
<%_ if (fieldsContainUUID || primaryKey.typeString || otherEntityPrimaryKeyTypesIncludesUUID) { _%>
import java.util.UUID;
<%_ } _%>
<%_ if (!embedded && primaryKey.hasLong) { _%>
import java.util.Random;
import java.util.concurrent.atomic.AtomicLong;
<%_ } _%>
<%_ if (fieldsContainBigDecimal) { _%>
import static <%= packageName %>.web.rest.TestUtil.sameNumber;
<%_ } _%>
<%_ if (fieldsContainZonedDateTime) { _%>
import static <%= packageName %>.web.rest.TestUtil.sameInstant;
<%_ } _%>
import static org.assertj.core.api.Assertions.assertThat;
<%_ if (searchEngineElasticsearch && !reactive) { _%>
import static org.elasticsearch.index.query.QueryBuilders.queryStringQuery;
<%_ } _%>
import static org.hamcrest.Matchers.hasItem;
<%_ if (reactive) { _%>
import static org.hamcrest.Matchers.is;
<%_ } _%>
<%_ if (testsNeedCsrf) { _%>
<%_ if (reactive) { _%>
import static org.springframework.security.test.web.reactive.server.SecurityMockServerConfigurers.csrf;
<%_ } else { _%>
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
<%_ } _%>
<%_ } _%>
<%_ if (searchEngineElasticsearch || fieldsContainOwnerManyToMany) { _%>
import static org.mockito.Mockito.*;
<%_ } _%>
<%_ if (!reactive) { _%>
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
<%_ } _%>
<%_ for (const field of fields.filter(field => !field.transient)) {
if (field.fieldIsEnum) { _%>
import <%= packageName %>.domain.enumeration.<%= field.fieldType %>;
<%_ }
} _%>
/**
* Integration tests for the {@link <%= entityClass %>Resource} REST controller.
*/
@IntegrationTest
<%_ if (cacheProviderRedis || searchEngineElasticsearch || fieldsContainOwnerManyToMany) { _%>
@ExtendWith(MockitoExtension.class)
<%_ } _%>
<%_ if (!reactive) { _%>
@AutoConfigureMockMvc
<%_ } else { _%>
@AutoConfigureWebTestClient
<%_ } _%>
@WithMockUser
class <%= entityClass %>ResourceIT <% if (databaseTypeCassandra) { %>extends AbstractCassandraTest <% } %>{
<%_
for (field of fields.filter(field => !field.id && !field.transient)) {
const defaultValueName = 'DEFAULT_' + field.fieldNameUnderscored.toUpperCase();
const updatedValueName = 'UPDATED_' + field.fieldNameUnderscored.toUpperCase();
const smallerValueName = 'SMALLER_' + field.fieldNameUnderscored.toUpperCase();
const needsSmallerValueName = jpaMetamodelFiltering && isFilterableType(field.fieldType)
&& (field.fieldTypeNumeric || field.fieldTypeDuration || field.fieldTypeLocalDate || field.fieldTypeZonedDateTime);
let defaultValue = 1;
let updatedValue = 2;
if (field.fieldValidate === true) {
if (field.fieldValidationMax) {
defaultValue = field.fieldValidateRulesMax;
updatedValue = parseInt(field.fieldValidateRulesMax) - 1;
}
if (field.fieldValidationMin) {
defaultValue = field.fieldValidateRulesMin;
updatedValue = parseInt(field.fieldValidateRulesMin) + 1;
}
if (field.fieldValidationMinBytes) {
defaultValue = field.fieldValidateRulesMinbytes;
updatedValue = field.fieldValidateRulesMinbytes;
}
if (field.fieldValidationMaxBytes) {
updatedValue = field.fieldValidateRulesMaxbytes;
}
}
const fieldType = field.fieldType;
const isEnum = field.fieldIsEnum;
let enumValue1;
let enumValue2;
if (isEnum) {
const enumValues = field.enumValues;
enumValue1 = enumValues[0];
if (enumValues.length > 1) {
enumValue2 = enumValues[1];
} else {
enumValue2 = enumValue1;
}
}
if (field.fieldTypeString || field.blobContentTypeText) {
// Generate Strings, using the min and max string length if they are configured
let sampleTextString = "";
let updatedTextString = "";
let sampleTextLength = 10;
if (field.fieldValidateRulesMinlength > sampleTextLength) {
sampleTextLength = field.fieldValidateRulesMinlength;
}
if (field.fieldValidateRulesMaxlength < sampleTextLength) {
sampleTextLength = field.fieldValidateRulesMaxlength;
}
for (let i = 0; i < sampleTextLength; i++) {
sampleTextString += "A";
updatedTextString += "B";
}
if (field.fieldValidateRulesPattern !== undefined) {
// Generate Strings, using pattern
try {
const patternRegExp = new RegExp(field.fieldValidateRulesPattern);
const randExp = field.createRandexp();
// set infinite repetitions max range
if (!patternRegExp.test(sampleTextString.replace(/\\"/g, '"').replace(/\\\\/g, '\\'))) {
sampleTextString = randExp.gen().replace(/\\/g, '\\\\').replace(/"/g, '\\"');
}
if (!patternRegExp.test(updatedTextString.replace(/\\"/g, '"').replace(/\\\\/g, '\\'))) {
updatedTextString = randExp.gen().replace(/\\/g, '\\\\').replace(/"/g, '\\"');
}
} catch (error) {
log(this.chalkRed('Error generating test value for entity "' + entityClass +
'" field "' + field.fieldName + '" with pattern "' + field.fieldValidateRulesPattern +
'", generating default values for this field. Detailed error message: "' + error.message + '".'));
}
if (sampleTextString === updatedTextString) {
updatedTextString = updatedTextString + "B";
log(this.chalkRed('Randomly generated first and second test values for entity "' + entityClass +
'" field "' + field.fieldName + '" with pattern "' + field.fieldValidateRulesPattern +
'" in file "' + entityClass + 'ResourceIT" where equal, added symbol "B" to second value.'));
}
} _%>
private static final String <%= defaultValueName %> = "<%- sampleTextString %>";
private static final String <%= updatedValueName %> = "<%- updatedTextString %>";
<%_ } else if (field.fieldTypeInteger) { _%>
private static final Integer <%= defaultValueName %> = <%= defaultValue %>;
private static final Integer <%= updatedValueName %> = <%= updatedValue %>;
<%_ if (needsSmallerValueName) { _%>
private static final Integer <%= smallerValueName %> = <%= defaultValue %> - 1;
<%_ } _%>
<%_ } else if (field.fieldTypeLong) { _%>
private static final Long <%= defaultValueName %> = <%= defaultValue %>L;
private static final Long <%= updatedValueName %> = <%= updatedValue %>L;
<%_ if (needsSmallerValueName) { _%>
private static final Long <%= smallerValueName %> = <%= defaultValue %>L - 1L;
<%_ } _%>
<%_ } else if (field.fieldTypeFloat) { _%>
private static final <%= fieldType %> <%= defaultValueName %> = <%= defaultValue %>F;
private static final <%= fieldType %> <%= updatedValueName %> = <%= updatedValue %>F;
<%_ if (needsSmallerValueName) { _%>
private static final <%= fieldType %> <%= smallerValueName %> = <%= defaultValue %>F - 1F;
<%_ } _%>
<%_ } else if (field.fieldTypeDouble) { _%>
private static final <%= fieldType %> <%= defaultValueName %> = <%= defaultValue %>D;
private static final <%= fieldType %> <%= updatedValueName %> = <%= updatedValue %>D;
<%_ if (needsSmallerValueName) { _%>
private static final <%= fieldType %> <%= smallerValueName %> = <%= defaultValue %>D - 1D;
<%_ } _%>
<%_ } else if (field.fieldTypeBigDecimal) { _%>
private static final BigDecimal <%= defaultValueName %> = new BigDecimal(<%= defaultValue %>);
private static final BigDecimal <%= updatedValueName %> = new BigDecimal(<%= updatedValue %>);
<%_ if (needsSmallerValueName) { _%>
private static final BigDecimal <%= smallerValueName %> = new BigDecimal(<%= defaultValue %> - 1);
<%_ } _%>
<%_ } else if (field.fieldTypeUUID) { _%>
private static final UUID <%= defaultValueName %> = UUID.randomUUID();
private static final UUID <%= updatedValueName %> = UUID.randomUUID();
<%_ } else if (field.fieldTypeLocalDate) { _%>
private static final LocalDate <%= defaultValueName %> = LocalDate.ofEpochDay(0L);
private static final LocalDate <%= updatedValueName %> = LocalDate.now(ZoneId.systemDefault());
<%_ if (needsSmallerValueName) { _%>
private static final LocalDate <%= smallerValueName %> = LocalDate.ofEpochDay(-1L);
<%_ } _%>
<%_ } else if (field.fieldTypeInstant) { _%>
private static final Instant <%= defaultValueName %> = Instant.ofEpochMilli(0L);
private static final Instant <%= updatedValueName %> = Instant.now().truncatedTo(ChronoUnit.MILLIS);
<%_ if (needsSmallerValueName) { _%>
private static final Instant <%= smallerValueName %> = Instant.ofEpochMilli(-1L);
<%_ } _%>
<%_ } else if (field.fieldTypeZonedDateTime) { _%>
private static final ZonedDateTime <%= defaultValueName %> = ZonedDateTime.ofInstant(Instant.ofEpochMilli(0L), ZoneOffset.UTC);
private static final ZonedDateTime <%= updatedValueName %> = ZonedDateTime.now(ZoneId.systemDefault()).withNano(0);
<%_ if (needsSmallerValueName) { _%>
private static final ZonedDateTime <%= smallerValueName %> = ZonedDateTime.ofInstant(Instant.ofEpochMilli(-1L), ZoneOffset.UTC);
<%_ } _%>
<%_ } else if (field.fieldTypeDuration) { _%>
private static final Duration <%= defaultValueName %> = Duration.ofHours(6);
private static final Duration <%= updatedValueName %> = Duration.ofHours(12);
<%_ if (needsSmallerValueName) { _%>
private static final Duration <%= smallerValueName %> = Duration.ofHours(5);
<%_ } _%>
<%_ } else if (field.fieldTypeBoolean) { _%>
private static final Boolean <%= defaultValueName %> = false;
private static final Boolean <%= updatedValueName %> = true;
<%_ } else if (field.fieldTypeBinary && !field.blobContentTypeText) { _%>
<%_ if (!databaseTypeCassandra) { _%>
private static final byte[] <%= defaultValueName %> = TestUtil.createByteArray(1, "0");
private static final byte[] <%= updatedValueName %> = TestUtil.createByteArray(1, "1");
<%_ } else { _%>
private static final ByteBuffer <%= defaultValueName %> = ByteBuffer.wrap(TestUtil.createByteArray(1, "0"));
private static final ByteBuffer <%= updatedValueName %> = ByteBuffer.wrap(TestUtil.createByteArray(1, "1"));
<%_ } _%>
private static final String <%= defaultValueName %>_CONTENT_TYPE = "image/jpg";
private static final String <%= updatedValueName %>_CONTENT_TYPE = "image/png";
<%_ } else if (isEnum) { _%>
private static final <%= fieldType %> <%= defaultValueName %> = <%= fieldType %>.<%= enumValue1.name %>;
private static final <%= fieldType %> <%= updatedValueName %> = <%= fieldType %>.<%= enumValue2.name %>;
<%_ }
} _%>
private static final String ENTITY_API_URL = "/api/<%= entityApiUrl %>";
private static final String ENTITY_API_URL_ID = ENTITY_API_URL + "/{<%= primaryKey.name %>}";
<%_ if (searchEngine) { _%>
private static final String ENTITY_SEARCH_API_URL = "/api/_search/<%= entityApiUrl %>";
<%_ } _%>
<%_ if (!embedded && primaryKey.hasLong) { _%>
private static Random random = new Random();
private static AtomicLong count = new AtomicLong(random.nextInt() + ( 2 * Integer.MAX_VALUE ));
<%_ } _%>
@Autowired
private <%= entityClass %>Repository <%= entityInstance %>Repository;
<%_ if (isUsingMapsId && (!dtoMapstruct && serviceNo)) { _%>
@Autowired
private <%= mapsIdEntity %>Repository <%= mapsIdRepoInstance %>;
<%_ } _%>
<%_ if (saveUserSnapshot) { _%>
@Autowired
private UserRepository userRepository;
<%_ } _%>
<%_ if (fieldsContainOwnerManyToMany) { _%>
@Mock
private <%= entityClass %>Repository <%= entityInstance %>RepositoryMock;
<%_ } _%>
<%_ if (dtoMapstruct) { _%>
@Autowired
private <%= entityClass %>Mapper <%= entityInstance %>Mapper;
<%_ } if (!serviceNo) { _%>
<%_ if (fieldsContainOwnerManyToMany) { _%>
@Mock
private <%= entityClass %>Service <%= entityInstance %>ServiceMock;
<%_ } _%>
<%_ } if (searchEngineElasticsearch) { _%>
/**
* This repository is mocked in the <%= packageName %>.repository.search test package.
*
* @see <%= packageName %>.repository.search.<%= entityClass %>SearchRepositoryMockConfiguration
*/
@Autowired
private <%= entityClass %>SearchRepository mock<%= entityClass %>SearchRepository;
<%_ } _%>
<%_ if (databaseTypeSql) { _%>
@Autowired
private EntityManager em;
<%_ } _%>
<%_ if (!reactive) { _%>
@Autowired
private MockMvc rest<%= entityClass %>MockMvc;
<%_ } else { _%>
@Autowired
private WebTestClient webTestClient;
<%_ } _%>
private <%= persistClass %> <%= persistInstance %>;
<%_ ['DEFAULT_', 'UPDATED_'].forEach((fieldStatus) => { _%>
/**
* Create an <% if (fieldStatus === 'UPDATED_') { %>updated <% } %>entity for this test.
*
* This is a static method, as tests for other entities might also need it,
* if they test an entity which requires the current entity.
*/
public static <%= persistClass %> create<% if (fieldStatus === 'UPDATED_') { _%>Updated<%_ } %>Entity(<% if (databaseTypeSql) { %>EntityManager em<% } %>) {
<%_ if (fluentMethods) { _%>
<%= persistClass %> <%= persistInstance %> = new <%= persistClass %>()<% for (field of fields.filter(field => !field.id && !field.transient)) { %>
.<%= field.fieldName %>(<%= fieldStatus + field.fieldNameUnderscored.toUpperCase() %>)<% if (field.fieldTypeBinary && !field.blobContentTypeText) { %>
.<%= field.fieldName %>ContentType(<%= fieldStatus + field.fieldNameUnderscored.toUpperCase() %>_CONTENT_TYPE)<% } %><% } %>;
<%_ } else { _%>
<%= persistClass %> <%= persistInstance %> = new <%= persistClass %>();
<%_ for (field of fields.filter(field => !field.id && !field.transient)) { _%>
<%= persistInstance %>.set<%= field.fieldInJavaBeanMethod %>(<%= fieldStatus + field.fieldNameUnderscored.toUpperCase() %>);
<%_ if (field.fieldTypeBinary && !field.blobContentTypeText) { _%>
<%= persistInstance %>.set<%= field.fieldInJavaBeanMethod %>ContentType(<%= fieldStatus + field.fieldNameUnderscored.toUpperCase() %>_CONTENT_TYPE);
<%_ } _%>
<%_ } _%>
<%_ } _%>
<%_
const alreadyGeneratedEntities = [];
for (relationship of relationships) {
const relationshipValidate = relationship.relationshipValidate;
const otherEntityName = relationship.otherEntityName;
const otherEntityNameCapitalized = relationship.otherEntityNameCapitalized;
const relationshipNameCapitalizedPlural = relationship.relationshipNameCapitalizedPlural;
const relationshipNameCapitalized = relationship.relationshipNameCapitalized;
const mapsIdUse = relationship.id;
if ((relationshipValidate !== null && relationshipValidate) || mapsIdUse) { _%>
// Add required entity
<%_ if (alreadyGeneratedEntities.indexOf(otherEntityName) == -1) { _%>
<%_ if (relationship.otherEntityUser) { /* TODO or other entity has no unique fields */ _%>
<%= asEntity(otherEntityNameCapitalized) %> <%= otherEntityName %> = <%= createEntityPrefix %><%= otherEntityNameCapitalized %>ResourceIT.createEntity(<% if (databaseTypeSql) { %>em<% } %>)<%= createEntityPostfix %>;
<%_ if (databaseTypeSql && !reactive) { _%>
em.persist(<%= otherEntityName %>);
em.flush();
<%_ } _%>
<%_ if (databaseTypeMongodb) { _%>
<%= otherEntityName %>.set<%= primaryKey.nameCapitalized %>("fixed-id-for-tests");
<%_ } _%>
<%_ } else { _%>
<%= asEntity(otherEntityNameCapitalized) %> <%= otherEntityName %>;
<%_ if (databaseTypeSql && !reactive) { _%>
if (TestUtil.findAll(em, <%= asEntity(otherEntityNameCapitalized) %>.class).isEmpty()) {
<%= otherEntityName %> = <%= createEntityPrefix %><%= otherEntityNameCapitalized %>ResourceIT.create<% if (fieldStatus === 'UPDATED_') { %>Updated<% } %>Entity(em)<%= createEntityPostfix %>;
em.persist(<%= otherEntityName %>);
em.flush();
} else {
<%= otherEntityName %> = TestUtil.findAll(em, <%= asEntity(otherEntityNameCapitalized) %>.class).get(0);
}
<%_ } else { _%>
<%= otherEntityName %> = <%= createEntityPrefix %><%= otherEntityNameCapitalized %>ResourceIT.create<% if (fieldStatus === 'UPDATED_') { %>Updated<% } %>Entity(<% if (databaseType === 'sql') { %>em<% } %>)<%= createEntityPostfix %>;
<%_ } _%>
<%_ if (databaseTypeMongodb) { _%>
<%= otherEntityName %>.set<%= primaryKey.nameCapitalized %>("fixed-id-for-tests");
<%_ } _%>
<%_ } _%>
<%_ } _%>
<%_ if (relationship.relationshipManyToMany || relationship.relationshipOneToMany) { _%>
<%= persistInstance %>.get<%= relationshipNameCapitalizedPlural %>().add(<%= otherEntityName %>);
<%_ } else { _%>
<%= persistInstance %>.set<%= relationshipNameCapitalized %>(<%= otherEntityName %>);
<%_ } _%>
<%_ alreadyGeneratedEntities.push(otherEntityName) _%>
<%_ } _%>
<%_ } _%>
return <%= persistInstance %>;
}
<%_ }); _%>
<%_ if (databaseTypeSql && reactive) {
const alreadyGeneratedDeletionCalls = [];
_%>
public static void deleteEntities(EntityManager em) {
try {
<%_ relationships.forEach(function(rel) {
if (rel.shouldWriteJoinTable) { _%>
em.deleteAll("<%= rel.joinTable.name %>").block();
<%_ } _%>
<%_ }); _%>
em.deleteAll(<%= entityClass %>.class).block();
} catch (Exception e) {
// It can fail, if other entities are still referring this - it will be removed later.
}
<%_ relationships.forEach(function(rel) {
if ((rel.relationshipValidate || rel.id) && !alreadyGeneratedDeletionCalls.includes(rel.otherEntityName)) { _%>
<%= rel.otherEntityNameCapitalized %>ResourceIT.deleteEntities(em);
<%_ alreadyGeneratedDeletionCalls.push(rel.otherEntityName);
}
}); _%>
}
@AfterEach
public void cleanup() {
deleteEntities(em);
}
<%_ } _%>
<%_ if (reactive && testsNeedCsrf) { _%>
@BeforeEach
public void setupCsrf() {
webTestClient = webTestClient.mutateWith(csrf());
}
<%_ } _%>
@BeforeEach
public void initTest() {
<%_ if (databaseTypeMongodb || databaseTypeCouchbase || databaseTypeCassandra || databaseTypeNeo4j) { _%>
<%= entityInstance %>Repository.deleteAll()<%= callBlock %>;
<%_ } else if (databaseTypeSql && reactive) { _%>
deleteEntities(em);
<%_ } _%>
<%= persistInstance %> = createEntity(<% if (databaseTypeSql) { %>em<% } %>);
}
<%_ if (!readOnly) { _%>
@Test<%= transactionalAnnotation %>
void create<%= entityClass %>() throws Exception {
int databaseSizeBeforeCreate = <%= entityInstance %>Repository.findAll()<%= callListBlock %>.size();
<%_ if (reactive && searchEngineElasticsearch) { _%>
// Configure the mock search repository
when(mock<%= entityClass %>SearchRepository.save(any()))
.thenAnswer(invocation -> Mono.just(invocation.getArgument(0)));
<%_ } _%>
// Create the <%= entityClass %>
<%_ if (dtoMapstruct) { _%>
<%= dtoClass %> <%= dtoInstance %> = <%= entityInstance %>Mapper.toDto(<%= persistInstance %>);
<%_ } _%>
<%_ if (!reactive) { _%>
rest<%= entityClass %>MockMvc.perform(post(ENTITY_API_URL)<% if (testsNeedCsrf) { %>.with(csrf())<% }%>
.contentType(MediaType.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(<%= restInstance %>)))
.andExpect(status().isCreated());
<%_ } else { _%>
webTestClient.post().uri(ENTITY_API_URL)
.contentType(MediaType.APPLICATION_JSON)
.bodyValue(TestUtil.convertObjectToJsonBytes(<%= restInstance %>))
.exchange()
.expectStatus().isCreated();
<%_ } _%>
// Validate the <%= entityClass %> in the database
<%_ if (databaseTypeCouchbase) { _%>
SecurityContextHolder.setContext(TestSecurityContextHolder.getContext());
<%_ } _%>
List<<%= persistClass %>> <%= entityInstance %>List = <%= entityInstance %>Repository.findAll()<%= callListBlock %>;
assertThat(<%= entityInstance %>List).hasSize(databaseSizeBeforeCreate + 1);
<%= persistClass %> test<%= entityClass %> = <%= entityInstance %>List.get(<%= entityInstance %>List.size() - 1);
<%_ for (const field of fields.filter(field => !field.id && !field.transient)) {
if (field.fieldTypeZonedDateTime) { _%>
assertThat(test<%= entityClass %>.get<%= field.fieldInJavaBeanMethod %>()).isEqualTo(<%= 'DEFAULT_' + field.fieldNameUnderscored.toUpperCase() %>);
<%_ } else if (field.fieldTypeBinary && !field.blobContentTypeText) { _%>
assertThat(test<%= entityClass %>.get<%= field.fieldInJavaBeanMethod %>()).isEqualTo(<%= 'DEFAULT_' + field.fieldNameUnderscored.toUpperCase() %>);
assertThat(test<%= entityClass %>.get<%= field.fieldInJavaBeanMethod %>ContentType()).isEqualTo(<%= 'DEFAULT_' + field.fieldNameUnderscored.toUpperCase() %>_CONTENT_TYPE);
<%_ } else if (field.fieldTypeBigDecimal) { _%>
assertThat(test<%= entityClass %>.get<%= field.fieldInJavaBeanMethod %>()).isEqualByComparingTo(<%= 'DEFAULT_' + field.fieldNameUnderscored.toUpperCase() %>);
<%_ } else { _%>
assertThat(test<%= entityClass %>.get<%= field.fieldInJavaBeanMethod %>()).isEqualTo(<%= 'DEFAULT_' + field.fieldNameUnderscored.toUpperCase() %>);
<%_ }
} _%>
<%_ if (isUsingMapsId) { _%>
// Validate the id for MapsId, the ids must be same
assertThat(test<%= entityClass %>.get<%= primaryKey.nameCapitalized %>()).isEqualTo(test<%= entityClass %>.get<%= mapsIdEntity %>().get<%= primaryKey.nameCapitalized %>());
<%_ } _%>
<%_ if (searchEngineElasticsearch) { _%>
// Validate the <%= entityClass %> in Elasticsearch
verify(mock<%= entityClass %>SearchRepository, times(1)).save(test<%= entityClass %>);
<%_ } _%>
}
@Test<%= transactionalAnnotation %>
void create<%= entityClass %>WithExistingId() throws Exception {
// Create the <%= entityClass %> with an existing ID
<%_ if (primaryKey.typeUUID && databaseTypeSql) { _%>
<%= entityInstance %>Repository.<%= saveMethod %>(<%= persistInstance %>)<%= callBlock %>;
<%_ } else { _%>
<%= persistInstance %>.set<%= primaryKey.nameCapitalized %>(<% if (primaryKey.typeUUID) { %>UUID.randomUUID()<% } else if (primaryKey.typeLong) { %>1L<% } else { %>"existing_id"<% } %>);
<%_ } _%>
<%_ if (dtoMapstruct) { _%>
<%= dtoClass %> <%= dtoInstance %> = <%= entityInstance %>Mapper.toDto(<%= persistInstance %>);
<%_ } _%>
int databaseSizeBeforeCreate = <%= entityInstance %>Repository.findAll()<%= callListBlock %>.size();
// An entity with an existing ID cannot be created, so this API call must fail
<%_ if (!reactive) { _%>
rest<%= entityClass %>MockMvc.perform(post(ENTITY_API_URL)<% if (testsNeedCsrf) { %>.with(csrf())<% }%>
.contentType(MediaType.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(<%= restInstance %>)))
.andExpect(status().isBadRequest());
<%_ } else { _%>
webTestClient.post().uri(ENTITY_API_URL)
.contentType(MediaType.APPLICATION_JSON)
.bodyValue(TestUtil.convertObjectToJsonBytes(<%= restInstance %>))
.exchange()
.expectStatus().isBadRequest();
<%_ } _%>
// Validate the <%= entityClass %> in the database
<%_ if (databaseTypeCouchbase) { _%>
SecurityContextHolder.setContext(TestSecurityContextHolder.getContext());
<%_ } _%>
List<<%= persistClass %>> <%= entityInstance %>List = <%= entityInstance %>Repository.findAll()<%= callListBlock %>;
assertThat(<%= entityInstance %>List).hasSize(databaseSizeBeforeCreate);
<%_ if (searchEngineElasticsearch) { _%>
// Validate the <%= entityClass %> in Elasticsearch
verify(mock<%= entityClass %>SearchRepository, times(0)).save(<%= persistInstance %>);
<%_ } _%>
}
<%_ if (databaseTypeSql && isUsingMapsId) { _%>
@Test<%= transactionalAnnotation %>
void update<%= entityClass %>MapsIdAssociationWithNewId() throws Exception {
// Initialize the database
<%= entityInstance %>Repository.<%= saveMethod %>(<%= persistInstance %>)<%= callBlock %>;
<%_ const alreadyGeneratedEntities = []; _%>
int databaseSizeBeforeCreate = <%= entityInstance %>Repository.findAll()<%= callListBlock %>.size();
<%_ for (relationship of relationships) {
const otherEntityName = relationship.otherEntityName;
const otherEntityNameCapitalized = relationship.otherEntityNameCapitalized;
const mapsIdUse = relationship.id;
if (mapsIdUse) { _%>
// Add a new parent entity
<%_ if (alreadyGeneratedEntities.indexOf(otherEntityName) == -1) { _%>
<%= asEntity(otherEntityNameCapitalized) %> <%= otherEntityName %> = <%= otherEntityNameCapitalized %>ResourceIT.create<% if (!relationship.otherEntityUser) { _%>Updated<%_ } %>Entity(<% if (databaseTypeSql) { %>em<% } %>);
<%_ if (databaseTypeSql && !reactive) { _%>
em.persist(<%= otherEntityName %>);
em.flush();
<%_ } _%>
<%_ } _%>
<%_ alreadyGeneratedEntities.push(otherEntityName) _%>
<%_ } _%>
<%_ break; } _%>
// Load the <%= entityInstance %>
<%= persistClass %> updated<%= persistClass %> = <%= entityInstance %>Repository.findById(<%= persistInstance %>.get<%= primaryKey.nameCapitalized %>())<%= reactive ? '.block()' : '.get()' %>;
assertThat(updated<%= persistClass %>).isNotNull();
<%_ if (databaseTypeSql && !reactive) { _%>
// Disconnect from session so that the updates on updated<%= persistClass %> are not directly saved in db
em.detach(updated<%= persistClass %>);
<%_ } _%>
// Update the <%= mapsIdEntity %> with new association value
updated<%= persistClass %>.set<%= mapsIdEntity %>(<%= alreadyGeneratedEntities.pop() %>);
<%_ if (dtoMapstruct) { _%>
<%= dtoClass %> updated<%= dtoClass %> = <%= entityInstance %>Mapper.toDto(updated<%= persistClass %>);
assertThat(updated<%= dtoClass %>).isNotNull();
<%_ } _%>
// Update the entity
<%_ if (reactive) { _%>
webTestClient.put().uri(ENTITY_API_URL_ID, <%_ if (dtoMapstruct) { _%>updated<%= dtoClass %> <%_ } else { _%> updated<%= persistClass %> <%_ } _%>.get<%= primaryKey.nameCapitalized %>())
.contentType(MediaType.APPLICATION_JSON)
.bodyValue(TestUtil.convertObjectToJsonBytes(<%_ if (dtoMapstruct) { _%>updated<%= dtoClass %> <%_ } else { _%> updated<%= persistClass %> <%_ } _%>))
.exchange()
.expectStatus().isOk();
<%_ } else { _%>
rest<%= entityClass %>MockMvc.perform(put(ENTITY_API_URL_ID, <%_ if (dtoMapstruct) { _%>updated<%= dtoClass %> <%_ } else { _%> updated<%= persistClass %> <%_ } _%>.get<%= primaryKey.nameCapitalized %>())<% if (testsNeedCsrf) { %>.with(csrf())<% }%>
.contentType(MediaType.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(<%_ if (dtoMapstruct) { _%>updated<%= dtoClass %> <%_ } else { _%> updated<%= persistClass %> <%_ } _%>)))
.andExpect(status().isOk());
<%_ } _%>
// Validate the <%= entityClass %> in the database
<%_ if (databaseTypeCouchbase) { _%>
SecurityContextHolder.setContext(TestSecurityContextHolder.getContext());
<%_ } _%>
List<<%= persistClass %>> <%= entityInstance %>List = <%= entityInstance %>Repository.findAll()<%= callListBlock %>;
assertThat(<%= entityInstance %>List).hasSize(databaseSizeBeforeCreate);
<%= persistClass %> test<%= entityClass %> = <%= entityInstance %>List.get(<%= entityInstance %>List.size() - 1);
// Validate the id for MapsId, the ids must be same
// Uncomment the following line for assertion. However, please note that there is a known issue and uncommenting will fail the test.
// Please look at https://github.com/jhipster/generator-jhipster/issues/9100. You can modify this test as necessary.
// assertThat(test<%= entityClass %>.get<%= primaryKey.nameCapitalized %>()).isEqualTo(test<%= entityClass %>.get<%= mapsIdEntity %>().get<%= primaryKey.nameCapitalized %>());
<%_ if (searchEngineElasticsearch) { _%>
// Validate the <%= entityClass %> in Elasticsearch
verify(mock<%= entityClass %>SearchRepository).save(<%= persistInstance %>);
<%_ } _%>
}
<%_ } _%>
<%_ for (field of fields.filter(field => !field.id && !field.transient)) { _%>
<%_ if (field.fieldValidate) {
let required = false;
if (!field.fieldTypeBytes && field.fieldValidate && field.fieldValidationRequired) {
required = true;
}
if (required) { _%>
@Test<%= transactionalAnnotation %>
void check<%= field.fieldInJavaBeanMethod %>IsRequired() throws Exception {
int databaseSizeBeforeTest = <%= entityInstance %>Repository.findAll()<%= callListBlock %>.size();
// set the field null
<%= persistInstance %>.set<%= field.fieldInJavaBeanMethod %>(null);
// Create the <%= entityClass %>, which fails.<% if (dtoMapstruct) { %>
<%= dtoClass %> <%= dtoInstance %> = <%= entityInstance %>Mapper.toDto(<%= persistInstance %>);<% } %>
<%_ if (!reactive) { _%>
rest<%= entityClass %>MockMvc.perform(post(ENTITY_API_URL)<% if (testsNeedCsrf) { %>.with(csrf())<% }%>
.contentType(MediaType.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(<%= restInstance %>)))
.andExpect(status().isBadRequest());
<%_ } else { _%>
webTestClient.post().uri(ENTITY_API_URL)
.contentType(MediaType.APPLICATION_JSON)
.bodyValue(TestUtil.convertObjectToJsonBytes(<%= restInstance %>))
.exchange()
.expectStatus().isBadRequest();
<%_ } _%>
<%_ if (databaseTypeCouchbase) { _%>
SecurityContextHolder.setContext(TestSecurityContextHolder.getContext());
<%_ } _%>
List<<%= persistClass %>> <%= entityInstance %>List = <%= entityInstance %>Repository.findAll()<%= callListBlock %>;
assertThat(<%= entityInstance %>List).hasSize(databaseSizeBeforeTest);
}
<%_ } _%>
<%_ } _%>
<%_ } _%>
<%_ } _%>
<%_ if (reactive && paginationNo) { _%>
@Test
void getAll<%= entityClassPlural %>AsStream() {
// Initialize the database
<%_ if (!primaryKey.derived) { _%>
<%_ for (field of primaryKey.fields.filter(f => !f.autoGenerateByRepository)) { _%>
<%= persistInstance %>.set<%= field.fieldNameCapitalized %>(<%- getJavaValueGeneratorForType(field.fieldType) %>);
<%_ } _%>
<%_ } _%>
<%= entityInstance %>Repository.save(<%= persistInstance %>)<%= callBlock %>;
List<<%= entityClass %>> <%= entityInstance %>List = webTestClient.get().uri(ENTITY_API_URL)
.accept(MediaType.APPLICATION_NDJSON)
.exchange()
.expectStatus().isOk()
.expectHeader().contentTypeCompatibleWith(MediaType.APPLICATION_NDJSON)
.returnResult(<%= restClass %>.class)
.getResponseBody()
<%_ if (dtoMapstruct) { _%>
.map(<%= entityInstance %>Mapper::toEntity)
<%_ } _%>
.filter(<%= persistInstance %>::equals)
.collectList()
.block(Duration.ofSeconds(5));
assertThat(<%= entityInstance %>List).isNotNull();
assertThat(<%= entityInstance %>List).hasSize(1);
<%= persistClass %> test<%= entityClass %> = <%= entityInstance %>List.get(0);
<%_ for (const field of fields.filter(field => !field.id && !field.transient)) {
if (field.fieldTypeZonedDateTime) { _%>
assertThat(test<%= entityClass %>.get<%= field.fieldInJavaBeanMethod %>()).isEqualTo(<%= 'DEFAULT_' + field.fieldNameUnderscored.toUpperCase() %>);
<%_ } else if ((field.fieldTypeBinary) && !field.blobContentTypeText) { _%>
assertThat(test<%= entityClass %>.get<%= field.fieldInJavaBeanMethod %>()).isEqualTo(<%= 'DEFAULT_' + field.fieldNameUnderscored.toUpperCase() %>);
assertThat(test<%= entityClass %>.get<%= field.fieldInJavaBeanMethod %>ContentType()).isEqualTo(<%= 'DEFAULT_' + field.fieldNameUnderscored.toUpperCase() %>_CONTENT_TYPE);
<%_ } else if (field.fieldTypeBigDecimal) { _%>
assertThat(test<%= entityClass %>.get<%= field.fieldInJavaBeanMethod %>()).isEqualByComparingTo(<%= 'DEFAULT_' + field.fieldNameUnderscored.toUpperCase() %>);
<%_ } else { _%>
assertThat(test<%= entityClass %>.get<%= field.fieldInJavaBeanMethod %>()).isEqualTo(<%= 'DEFAULT_' + field.fieldNameUnderscored.toUpperCase() %>);
<%_ }
} _%>
}
<%_ } _%>
@Test<%= transactionalAnnotation %>
void getAll<%= entityClassPlural %>() <% if (!reactive) { %>throws Exception <% } %>{
// Initialize the database
<%_ if (!primaryKey.derived) { _%>
<%_ for (field of primaryKey.fields.filter(f => !f.autoGenerateByRepository)) { _%>
<%= persistInstance %>.set<%= field.fieldNameCapitalized %>(<%- getJavaValueGeneratorForType(field.fieldType) %>);
<%_ } _%>
<%_ } _%>
<%= entityInstance %>Repository.<%= saveMethod %>(<%= persistInstance %>)<%= callBlock %>;
// Get all the <%= entityInstance %>List
<%_ if (!reactive) { _%>
rest<%= entityClass %>MockMvc.perform(get(ENTITY_API_URL<% if (!databaseTypeCassandra) { %> + "?sort=<%= primaryKey.name %>,desc"<% } %>))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
<%_ } else { _%>
webTestClient.get().uri(ENTITY_API_URL + "?sort=<%= primaryKey.name %>,desc")
.accept(MediaType.APPLICATION_JSON)
.exchange()
.expectStatus().isOk()
.expectHeader().contentType(MediaType.APPLICATION_JSON)
.expectBody()
<%_ } _%>
<%_ if (databaseTypeSql || databaseTypeMongodb || databaseTypeCouchbase || databaseTypeCassandra) { _%>
<%= !reactive ? '.andExpect(' : '.' %>jsonPath("$.[*].<%= primaryKey.name %>").value(hasItem(<%= idValue %>))<%= !reactive ? ')' : '' %><%_ } _%><% for (field of fields.filter(field => !field.id && !field.transient)) { %>
<%_ if (field.fieldTypeBinary && !field.blobContentTypeText) { _%>
<%= !reactive ? '.andExpect(' : '.' %>jsonPath("$.[*].<%= field.fieldName %>ContentType").value(hasItem(<%= 'DEFAULT_' + field.fieldNameUnderscored.toUpperCase() %>_CONTENT_TYPE))<%= !reactive ? ')' : '' %>
<%_ } _%>
<%= !reactive ? '.andExpect(' : '.' %>jsonPath("$.[*].<%= field.fieldName %>").value(hasItem(<%
if (field.fieldTypeBinary && !field.blobContentTypeText) { %>Base64Utils.encodeToString(<% } else
if (field.fieldTypeZonedDateTime) { %>sameInstant(<% } else
if (field.fieldTypeBigDecimal) { %>sameNumber(<% } %><%= 'DEFAULT_' + field.fieldNameUnderscored.toUpperCase() %><%
if (field.fieldTypeBinary && !field.blobContentTypeText) { %><%
if (databaseTypeCassandra) { %>.array()<% } %>)<% } else
if (field.fieldTypeInteger) { %><% } else
if (field.fieldTypeLong) { %>.intValue()<% } else
if (field.fieldTypeFloat || field.fieldTypeDouble) { %>.doubleValue()<% } else
if (field.fieldTypeBigDecimal) { %>)<% } else
if (field.fieldTypeBoolean) { %>.booleanValue()<% } else
if (field.fieldTypeZonedDateTime) { %>)<% } else
if (!field.fieldTypeString) { %>.toString()<% } %>))<%= !reactive ? ')' : '' %><%_ } _%>;
}
<% if (fieldsContainOwnerManyToMany && !databaseTypeNeo4j) { %>
@SuppressWarnings({"unchecked"})
void getAll<%= entityClassPlural %>WithEagerRelationshipsIsEnabled() <% if (!reactive) { %>throws Exception <% } %>{
<%_ if (!serviceNo) { _%>
when(<%= entityInstance %>ServiceMock.findAllWithEagerRelationships(any())).thenReturn(<% if (!reactive) { %>new PageImpl(new ArrayList<>())<% } else { %>Flux.empty()<% }%>);
<%_ } else { _%>
when(<%= entityInstance %>RepositoryMock.findAllWithEagerRelationships(any())).thenReturn(<% if (!reactive) { %>new PageImpl(new ArrayList<>())<% } else { %>Flux.empty()<% }%>);
<%_ } _%>
<%_ if (!reactive) { _%>
rest<%= entityClass %>MockMvc.perform(get(ENTITY_API_URL + "?eagerload=true"))
.andExpect(status().isOk());
<%_ } else { _%>
webTestClient.get().uri(ENTITY_API_URL + "?eagerload=true")
.exchange()
.expectStatus().isOk();
<%_ } _%>
<%_ if (!serviceNo) { _%>
verify(<%= entityInstance %>ServiceMock, times(1)).findAllWithEagerRelationships(any());
<%_ } else { _%>
verify(<%= entityInstance %>RepositoryMock, times(1)).findAllWithEagerRelationships(any());
<%_ } _%>
}
@SuppressWarnings({"unchecked"})
void getAll<%= entityClassPlural %>WithEagerRelationshipsIsNotEnabled() <% if (!reactive) { %>throws Exception <% } %>{
<%_ if (!serviceNo) { _%>
when(<%= entityInstance %>ServiceMock.findAllWithEagerRelationships(any())).thenReturn(<% if (!reactive) { %>new PageImpl(new ArrayList<>())<% } else { %>Flux.empty()<% }%>);
<%_ } else { _%>
when(<%= entityInstance %>RepositoryMock.findAllWithEagerRelationships(any())).thenReturn(<% if (!reactive) { %>new PageImpl(new ArrayList<>())<% } else { %>Flux.empty()<% }%>);
<%_ } _%>
<%_ if (!reactive) { _%>
rest<%= entityClass %>MockMvc.perform(get(ENTITY_API_URL + "?eagerload=true"))
.andExpect(status().isOk());
<%_ } else { _%>
webTestClient.get().uri(ENTITY_API_URL + "?eagerload=true")
.exchange()
.expectStatus().isOk();
<%_ } _%>
<%_ if (!serviceNo) { _%>
verify(<%= entityInstance %>ServiceMock, times(1)).findAllWithEagerRelationships(any());
<%_ } else { _%>
verify(<%= entityInstance %>RepositoryMock, times(1)).findAllWithEagerRelationships(any());
<%_ } _%>
}
<%_ } _%>
@Test<%= transactionalAnnotation %>
void get<%= entityClass %>() <% if (!reactive) { %>throws Exception <% } %>{
// Initialize the database
<%_ if (!primaryKey.derived) { _%>
<%_ for (field of primaryKey.fields.filter(f => !f.autoGenerateByRepository)) { _%>
<%= persistInstance %>.set<%= field.fieldNameCapitalized %>(<%- getJavaValueGeneratorForType(field.fieldType) %>);
<%_ } _%>
<%_ } _%>
<%= entityInstance %>Repository.<%= saveMethod %>(<%= persistInstance %>)<%= callBlock %>;
// Get the <%= entityInstance %>
<%_ if (!reactive) { _%>
rest<%= entityClass %>MockMvc.perform(get(ENTITY_API_URL_ID, <%= persistInstance %>.get<%= primaryKey.nameCapitalized %>()))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
<%_ } else { _%>
webTestClient.get().uri(ENTITY_API_URL_ID, <%= persistInstance %>.get<%= primaryKey.nameCapitalized %>())
.accept(MediaType.APPLICATION_JSON)
.exchange()
.expectStatus().isOk()
.expectHeader().contentType(MediaType.APPLICATION_JSON)
.expectBody()
<%_ } _%>
<%_ if (databaseTypeSql || databaseTypeMongodb || databaseTypeCouchbase || databaseTypeCassandra) { _%>
<%= !reactive ? '.andExpect(' : '.' %>jsonPath("$.<%= primaryKey.name %>").value(<%= reactive ? 'is(' : '' %><%= idValue %>))<%_ } _%><% for (field of fields.filter(field => !field.id && !field.transient)) { %>
<%_ if (field.fieldTypeBinary && !field.blobContentTypeText) { _%>
<%= !reactive ? '.andExpect(' : '.' %>jsonPath("$.<%= field.fieldName %>ContentType").value(<%= reactive ? 'is(' : '' %><%= 'DEFAULT_' + field.fieldNameUnderscored.toUpperCase() %>_CONTENT_TYPE))
<%_ } _%>
<%= !reactive ? '.andExpect(' : '.' %>jsonPath("$.<%= field.fieldName %>").value(<%= reactive ? 'is(' : '' %><%
if (field.fieldTypeBinary && !field.blobContentTypeText) { %>Base64Utils.encodeToString(<% } else
if (field.fieldTypeZonedDateTime) { %>sameInstant(<% } else
if (field.fieldTypeBigDecimal) { %>sameNumber(<% } %><%= 'DEFAULT_' + field.fieldNameUnderscored.toUpperCase() %><%
if (field.fieldTypeBinary && !field.blobContentTypeText) { %><%
if (databaseTypeCassandra) { %>.array()<% } %>)<% } else
if (field.fieldTypeInteger) { %><% } else
if (field.fieldTypeLong) { %>.intValue()<% } else
if (field.fieldTypeFloat || field.fieldTypeDouble) { %>.doubleValue()<% } else
if (field.fieldTypeBigDecimal) { %>)<% } else
if (field.fieldTypeBoolean) { %>.booleanValue()<% } else
if (field.fieldTypeZonedDateTime) { %>)<% } else
if (!field.fieldTypeString) { %>.toString()<% } %>))<%_ } _%>;
}
<%_ if (jpaMetamodelFiltering) { %>
@Test<%= transactionalAnnotation %>
void get<%= entityClassPlural %>ByIdFiltering() <% if (!reactive) { %>throws Exception <% } %>{
// Initialize the database
<%= entityInstance %>Repository.<%= saveMethod %>(<%= persistInstance %>)<%= callBlock %>;
<%= primaryKey.type %> id = <%= persistInstance %>.get<%= primaryKey.nameCapitalized %>();
default<%= entityClass %>ShouldBeFound("<%= primaryKey.name %>.equals=" + id);
default<%= entityClass %>ShouldNotBeFound("<%= primaryKey.name %>.notEquals=" + id);
<%_ if (primaryKey.typeLong) { _%>
default<%= entityClass %>ShouldBeFound("<%= primaryKey.name %>.greaterThanOrEqual=" + id);
default<%= entityClass %>ShouldNotBeFound("<%= primaryKey.name %>.greaterThan=" + id);
default<%= entityClass %>ShouldBeFound("<%= primaryKey.name %>.lessThanOrEqual=" + id);
default<%= entityClass %>ShouldNotBeFound("<%= primaryKey.name %>.lessThan=" + id);
<%_ } _%>
}