<%#
 Copyright 2013-2023 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 <%= entityAbsolutePackage %>.web.rest;

<%_
const saveMethodName = ormTool !== 'mybatis' ? 'saveAndFlush' : 'insert';
var filterTestableRelationships = reactive ? reactiveEagerRelations : relationships;
const fieldsToTest = fields.filter(field => !field.id && !field.autoGenerate && !field.transient);
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 && ormTool === 'hibernate') {
  saveMethod = 'saveAndFlush';
}
let createEntityPrefix = '';
let createEntityPostfix = '';
if (databaseTypeSql && reactive) {
  createEntityPrefix = 'em.insert(';
  createEntityPostfix = ').block()';
}
let idValue = `${persistInstance}.get${primaryKey.nameCapitalized}()`;
if (primaryKey.typeLong || primaryKey.typeInteger) {
  idValue = idValue + '.intValue()';
} else if (primaryKey.typeUUID) {
  idValue = idValue + '.toString()';
}
let transactionalAnnotation = '';
if (databaseTypeSql && !reactive) {
  transactionalAnnotation = '\n    @Transactional';
}

_%>
<%_ if (entityAbsolutePackage !== packageName) { _%>
import <%= packageName %>.web.rest.TestUtil;
<% } %>
import <%= packageName %>.IntegrationTest;
import <%= entityAbsolutePackage %>.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 (relationship.bcConfig && relationship.bcConfig.unidirectionSkip) {
    imported.push(otherEntityNameCapitalized);
  }
  if ((applicationTypeMicroservice && !(relationship.otherEntity.applications.includes('*') || relationship.otherEntity.applications.includes(baseName)))) {
    imported.push(otherEntityNameCapitalized);
  }
  if (imported.indexOf(otherEntityNameCapitalized) === -1) {
    if ((relationshipValidate !== null && relationshipValidate === true) || jpaMetamodelFiltering || (isUsingMapsIdL1 === true)) { _%>
        <%_
        if (!(((applicationTypeMonolith || applicationTypeMicroservice) && multiModule && moduleName && moduleName !== relationship.otherEntity.moduleName) ||
                (applicationTypeMicroservice && !(relationship.otherEntity.applications.includes('*') || relationship.otherEntity.applications.includes(baseName))))
        ) {
        _%>
import <%= relationship.otherEntity.entityAbsolutePackage %>.domain.<%= relationship.otherEntity.persistClass %>;
import <%= relationship.otherEntity.entityAbsolutePackage %>.repository.<%= relationship.otherEntity.persistClass %>Repository;
import <%= relationship.otherEntity.entityAbsolutePackage %>.web.rest.<%= relationship.otherEntity.persistClass %>ResourceIT;
        <%_ } _%>
<%_
          imported.push(otherEntityNameCapitalized);
    }
  }
} _%>
<%_
if(jpaMetamodelFiltering && reactive) {
  filterTestableRelationships.forEach(relationship => { _%>
import <%= relationship.otherEntity.entityAbsolutePackage %>.repository.<%= relationship.otherEntityNameCapitalized %>Repository;
import <%= relationship.otherEntity.entityAbsolutePackage %>.web.rest.<%= relationship.otherEntityNameCapitalized %>ResourceIT;
<%_ });
 } _%>
<%_ if (saveUserSnapshot) { _%>
import <%= entityAbsolutePackage %>.repository.UserRepository;
<%_ } _%>
import <%= entityAbsolutePackage %>.repository.<%= entityClass %>Repository;
<%_ if (databaseTypeSql && reactive && ormTool === 'hibernate') { _%>
import <%= packageName %>.repository.EntityManager;
<%_ } _%>
<%_ if (isUsingMapsId && (!dtoMapstruct && serviceNo)) { _%>
import <%= entityAbsolutePackage %>.repository.<%= mapsIdAssoc.otherEntityNameCapitalized %>Repository;
<%_ } _%>
<%_ if (searchEngineElasticsearch) { _%>
import <%= entityAbsolutePackage %>.repository.search.<%= entityClass %>SearchRepository;
<%_ } _%>
<%_ if (!serviceNo && implementsEagerLoadApis) { _%>
import <%= entityAbsolutePackage %>.service.<%= entityClass %>Service;
<%_ } _%>
<%_ if (dtoMapstruct) { _%>
import <%= entityAbsolutePackage %>.service.dto.<%= dtoClass %>;
import <%= entityAbsolutePackage %>.service.mapper.<%= entityClass %>Mapper;
<%_ } _%>
<%_ if (jpaMetamodelFiltering & !reactive) { _%>
import <%= entityAbsolutePackage %>.service.criteria.<%= entityClass %>Criteria;
<%_ } _%>
<%_ if (moduleName) { _%>
import <%= packageName %>.web.rest.TestUtil;
<%_ } _%>
<%_ if (searchEngineElasticsearch) { _%>
import org.assertj.core.util.IterableUtil;
import org.apache.commons.collections4.IterableUtils;
import java.util.concurrent.TimeUnit;
<%_ } _%>
<%_ if ((databaseTypeSql && reactive) || searchEngineElasticsearch) { _%>
import org.junit.jupiter.api.AfterEach;
<%_ } _%>
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
<%_ if (implementsEagerLoadApis || databaseTypeNeo4j) { _%>
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.reactive.AutoConfigureWebTestClient;
<%_ } else { _%>
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
<%_ } _%>
<%_ if (searchEngineElasticsearch && !paginationNo || implementsEagerLoadApis) { _%>
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
<%_ if (ormTool === 'hibernate') { _%>
import org.springframework.data.domain.Pageable;
<%_ } else { _%>
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
<%_ } _%>
<%_ } _%>
import org.springframework.http.MediaType;
<%_ if (searchEngineCouchbase) { _%>
import java.util.concurrent.TimeUnit;

import org.junit.jupiter.api.Timeout;
<%_ } _%>
<%_ 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) { _%>
import org.springframework.transaction.annotation.Transactional;
  <%_ } _%>
<%_ } _%>
<%_ if (anyFieldIsBlobDerived) { _%>
import org.springframework.util.Base64Utils;
<%_ } _%>
<%_ if (reactive && (implementsEagerLoadApis || searchEngineElasticsearch)) { _%>
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
<%_ } _%>
<%_ if (databaseTypeSql && !reactive && ormTool === 'hibernate') { _%>
import <%= javaVersion === '17' ? 'jakarta' : 'javax'%>.persistence.EntityManager;
<%_ } _%>
<%_ if (anyFieldIsBigDecimal) { _%>
import java.math.BigDecimal;
<%_ } _%>
<%_ if (anyFieldIsBlobDerived && databaseTypeCassandra) { _%>
import java.nio.ByteBuffer;
<%_ } _%>
<%_ if (reactive || anyFieldIsDuration) { _%>
import java.time.Duration;
<%_ } _%>
<%_ if (anyFieldIsLocalDate) { _%>
import java.time.LocalDate;
<%_ } _%>
<%_ if (anyFieldIsInstant || anyFieldIsZonedDateTime) { _%>
import java.time.Instant;
<%_ } _%>
<%_ if (anyFieldIsZonedDateTime) { _%>
import java.time.ZonedDateTime;
import java.time.ZoneOffset;
<%_ } _%>
<%_ if (anyFieldIsLocalDate || anyFieldIsZonedDateTime) { _%>
import java.time.ZoneId;
<%_ } _%>
<%_ if (anyFieldIsInstant) { _%>
import java.time.temporal.ChronoUnit;
<%_ } _%>
<%_ if (!reactive && implementsEagerLoadApis) { _%>
import java.util.ArrayList;
<%_ } _%>
<%_ if (searchEngineElasticsearch && !reactive) { _%>
import java.util.Collections;
  <%_ if (paginationNo) { _%>
import java.util.stream.Stream;
  <%_ } _%>
<%_ } _%>
import java.util.List;
<%_ if (javaVersion === '8') { _%>
import java.util.NoSuchElementException;
<%_ } _%>
<%_ if (anyFieldIsUUID || primaryKey.typeString || otherEntityPrimaryKeyTypesIncludesUUID) { _%>
import java.util.UUID;
<%_ } _%>
<%_ if (!embedded && (primaryKey.hasLong || primaryKey.hasInteger)) { _%>
import java.util.Random;
  <%_ if (primaryKey.hasLong) { _%>
import java.util.concurrent.atomic.AtomicLong;
  <%_ } else if (primaryKey.hasInteger) { _%>
import java.util.concurrent.atomic.AtomicInteger;
  <%_ } _%>
<%_ } _%>

<%_ if (anyFieldIsBigDecimal) { _%>
import static <%= packageName %>.web.rest.TestUtil.sameNumber;
<%_ } _%>
<%_ if (anyFieldIsZonedDateTime) { _%>
import static <%= packageName %>.web.rest.TestUtil.sameInstant;
<%_ } _%>
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.hasItem;
<%_ if (reactive) { _%>
import static org.hamcrest.Matchers.is;
<%_ } _%>
<%_ if (authenticationUsesCsrf) { _%>
  <%_ 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 || implementsEagerLoadApis) { _%>
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.*;
<%_ } _%>
<%_ if (searchEngineElasticsearch) { _%>
import static org.awaitility.Awaitility.await;
<%_ } _%>
<%_ 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 (implementsEagerLoadApis) { _%>
@ExtendWith(MockitoExtension.class)
<%_ } _%>
<%_ if (reactive) { _%>
@AutoConfigureWebTestClient(timeout = IntegrationTest.DEFAULT_ENTITY_TIMEOUT)
<%_ } else { _%>
@AutoConfigureMockMvc
<%_ } _%>
@WithMockUser
public class <%= entityClass %>ResourceIT {
<%_
for (field of fieldsToTest) {
const defaultValueName = 'DEFAULT_' + field.fieldNameUnderscored.toUpperCase();
const updatedValueName = 'UPDATED_' + field.fieldNameUnderscored.toUpperCase();
const smallerValueName = 'SMALLER_' + field.fieldNameUnderscored.toUpperCase();
const needsSmallerValueName = jpaMetamodelFiltering && field.filterableField
        && (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 && (!field.options || !field.options.customWrapType)) { _%>

    <%_ 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 (field.fieldTypeBlobContent === 'any' && !field.fieldWithContentType && field.options && field.options.customWrapType) { _%>
    <%_ if (fieldType.indexOf('[]') !== -1) { _%>
    private static final <%= fieldType%> <%= defaultValueName %> = {};
    private static final <%= fieldType%> <%= updatedValueName %> = {};
    <%_ } _%>
  <%_ } 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 (searchEngineAny) { _%>
    private static final String ENTITY_SEARCH_API_URL = "/api/_search/<%= entityApiUrl %>";
<%_ } _%>
<%_ if (!embedded && (primaryKey.hasLong || primaryKey.hasInteger)) { _%>

    private static Random random = new Random();
  <%_ if (primaryKey.hasLong) { _%>
    private static AtomicLong count = new AtomicLong(random.nextInt() + ( 2 * Integer.MAX_VALUE ));
  <%_ } else if (primaryKey.hasInteger) { _%>
    private static AtomicInteger count = new AtomicInteger(random.nextInt() + ( 2 * Short.MAX_VALUE ));
  <%_ } _%>
<%_ } _%>

    @Autowired
    private <%= entityClass %>Repository <%= entityInstance %>Repository;
<%_ if (isUsingMapsId && (!dtoMapstruct && serviceNo)) { _%>
    @Autowired
    private <%= mapsIdEntity %>Repository <%= mapsIdRepoInstance %>;
<%_ } _%>
<%_ if (saveUserSnapshot) { _%>

    @Autowired
    private UserRepository userRepository;
<%_ } _%>
<%_ if (implementsEagerLoadApis) { _%>

    @Mock
    private <%= entityClass %>Repository <%= entityInstance %>RepositoryMock;
<%_ } _%>
<%_ if (dtoMapstruct) { _%>

    @Autowired
    private <%= entityClass %>Mapper <%= entityInstance %>Mapper;
<%_ } if (!serviceNo) { _%>
  <%_ if (implementsEagerLoadApis) { _%>

    @Mock
    private <%= entityClass %>Service <%= entityInstance %>ServiceMock;
  <%_ } _%>

  <%_ if (entityClass !== 'CommonCondition' && databaseTypeSql && false) { _%>

    @Autowired
    private CommonConditionQueryService commonConditionQueryService;
  <%_ } _%>
<%_ } if (searchEngineElasticsearch) { _%>

    @Autowired
    private <%= entityClass %>SearchRepository <%= entityInstance %>SearchRepository;
<%_ } _%>
<%_ if (databaseTypeSql && ormTool === 'hibernate') { _%>

    @Autowired
    private EntityManager em;
<%_ } _%>

    @Autowired
<%_ if (reactive) { _%>
    private WebTestClient webTestClient;
<%_ } else { _%>
    private MockMvc rest<%= entityClass %>MockMvc;
<%_ } _%>

    private <%= persistClass %> <%= persistInstance %>;

<%_ if (jpaMetamodelFiltering && reactive) {
filterTestableRelationships.forEach((relationship) => { _%>
    @Autowired
    private <%= relationship.otherEntity.persistClass %>Repository <%= relationship.otherEntity.persistInstance %>Repository;
<%_ });
} _%>
<%_ if (ormTool === 'mybatis') { _%>
  <%_ relationships.filter(relationship => relationship.relationshipValidate || relationship.id).forEach(relationship => { _%>
    @Autowired
    private <%= relationship.otherEntity.persistClass %>Repository <%= relationship.otherEntity.persistInstance %>Repository;
  <%_ }); _%>
<%_ } _%>
<%_ ['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 && ormTool === 'hibernate') { %>EntityManager em<% } %>) {
  <%_ if (fluentMethods) { _%>
        <%= persistClass %> <%= persistInstance %> = new <%= persistClass %>()<%_ if (reactive && databaseTypeSql && primaryKey.typeUUID && !isUsingMapsId) { _%>
            .<%= primaryKey.name %>(UUID.randomUUID())
  <%_ } _%><% for (field of fieldsToTest) { %>
            .<%= 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 %>();
    <%_ if (reactive && databaseTypeSql && primaryKey.typeUUID && !isUsingMapsId) { _%>
        <%= persistInstance %>.set<%= primaryKey.fields[0].fieldInJavaBeanMethod %>(UUID.randomUUID());
    <%_ } _%>
    <%_ for (field of fieldsToTest) { _%>
        <%= 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 otherEntityInstance = relationship.otherEntity.entityInstance;
    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 */ _%>
        <%= relationship.otherEntity.persistClass %> <%= otherEntityName %> = <%= createEntityPrefix %><%= otherEntityNameCapitalized %>ResourceIT.createEntity(<% if (databaseTypeSql && ormTool === 'hibernate') { %>em<% } %>)<%= createEntityPostfix %>;
          <%_ if (databaseTypeSql && !reactive && ormTool === 'hibernate') { _%>
        em.persist(<%= otherEntityName %>);
        em.flush();
          <%_ } _%>
          <%_ if (databaseTypeMongodb) { _%>
        <%= otherEntityName %>.set<%= primaryKey.nameCapitalized %>("fixed-id-for-tests");
          <%_ } _%>
        <%_ } else { _%>
        <%= relationship.otherEntity.persistClass %> <%= otherEntityName %><% if (ormTool === 'mybatis') { %>= <%= createEntityPrefix %><%= otherEntityNameCapitalized %>ResourceIT.create<% if (fieldStatus === 'UPDATED_') { %>Updated<% } %>Entity(<% if (ormTool === 'hibernate') { %>em<% } %>)<%= createEntityPostfix %><% } %>;
          <%_ if (ormTool === 'hibernate') { _%>
          <%_ if (databaseTypeSql && !reactive) { _%>
            <%_ if (!isUsingMapsId || fieldStatus !== "UPDATED_") { _%>
        if (<% if (ormTool === 'hibernate') { %>TestUtil.findAll(em, <%= relationship.otherEntity.persistClass %>.class).isEmpty()<% } else { %><%= otherEntityInstance %>Repository.findAll() == null<% } %>) {
            <%_ } _%>
            <%= otherEntityName %> = <%= createEntityPrefix %><%= otherEntityNameCapitalized %>ResourceIT.create<% if (fieldStatus === 'UPDATED_') { %>Updated<% } %>Entity(<% if (ormTool === 'hibernate') { %>em<% } %>)<%= createEntityPostfix %>;
            <%_ if (ormTool === 'hibernate') { _%>
            em.persist(<%= otherEntityName %>);
            em.flush();
            <%_ } _%>
            <%_ if (!isUsingMapsId || fieldStatus !== "UPDATED_") { _%>
        } else {
            <%= otherEntityName %> = <% if (ormTool === 'hibernate') { %>TestUtil.findAll(em, <%= relationship.otherEntity.persistClass %>.class)<% } else { _%><%= otherEntityInstance %>Repository.findAll()<% } %>.get(0);
        }
            <%_ } _%>
          <%_ } else { _%>
        <%= otherEntityName %> = <%= createEntityPrefix %><%= otherEntityNameCapitalized %>ResourceIT.create<% if (fieldStatus === 'UPDATED_') { %>Updated<% } %>Entity(<% if (databaseTypeSql) { %>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(<%= persistClass %>.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 (searchEngineElasticsearch) { _%>
    @AfterEach
    public void cleanupElasticSearchRepository() {
        <%= entityInstance %>SearchRepository.deleteAll()<%= callBlock %>;
        assertThat(<%= entityInstance %>SearchRepository.count()<%= callBlock %>).isEqualTo(0);
    }

<%_ } _%>
<%_ if (reactive && authenticationUsesCsrf) { _%>
    @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 && ormTool === 'hibernate') { %>em<% } %>);
    }
<%_ if (!readOnly) { _%>

    @Test<%= transactionalAnnotation %>
    void create<%= entityClass %>() throws Exception {
        int databaseSizeBeforeCreate = <%= entityInstance %>Repository.findAll()<%= callListBlock %>.size();
  <%_ if (searchEngineElasticsearch) { _%>
        int searchDatabaseSizeBefore = IterableUtil.sizeOf(<%= entityInstance %>SearchRepository.findAll()<%= callListBlock %>);
  <%_ } _%>
  <%_
      // overwrite the id field again with null
      // the create method here is supposed to be used for other tests as well,
      // which may expect an id to be set (at least in the reactive stack)
      if (reactive && databaseTypeSql && primaryKey.typeUUID && !isUsingMapsId) { _%>
        <%= persistInstance %>.set<%= primaryKey.nameCapitalized %>(null);
  <%_ } _%>
        // Create the <%= entityClass %>
  <%_ if (dtoMapstruct) { _%>
        <%= dtoClass %> <%= dtoInstance %> = <%= entityInstance %>Mapper.toDto(<%= persistInstance %>);
  <%_ } _%>
  <%_ if (reactive) { _%>
        webTestClient.post().uri(ENTITY_API_URL)
            .contentType(MediaType.APPLICATION_JSON)
            .bodyValue(TestUtil.convertObjectToJsonBytes(<%= restInstance %>))
            .exchange()
            .expectStatus().isCreated();
  <%_ } else { _%>
        rest<%= entityClass %>MockMvc.perform(post(ENTITY_API_URL)<% if (authenticationUsesCsrf) { %>.with(csrf())<% }%>
            .contentType(MediaType.APPLICATION_JSON)
            .content(TestUtil.convertObjectToJsonBytes(<%= restInstance %>)))
            .andExpect(status().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);
  <%_ if (searchEngineElasticsearch) { _%>
        await().atMost(5, TimeUnit.SECONDS).untilAsserted(() -> {
            int searchDatabaseSizeAfter = IterableUtil.sizeOf(<%= entityInstance %>SearchRepository.findAll()<%= callListBlock %>);
            assertThat(searchDatabaseSizeAfter).isEqualTo(searchDatabaseSizeBefore + 1);
        });
  <%_ } _%>
        <%= persistClass %> test<%= entityClass %> = <%= entityInstance %>List.get(<%= entityInstance %>List.size() - 1);
  <%_ for (const field of fieldsToTest) {
    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() %>);
          <%_ if (!field.options || !field.options.customWrapType) { _%>
        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(<%_ if (dtoMapstruct) { _%><%= dtoInstance %><%_ } else { _%>test<%= entityClass %><%_ } _%>.get<%= mapsIdEntity %>().get<%= primaryKey.nameCapitalized %>());
  <%_ } _%>
    }

    @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 if (primaryKey.typeInteger) { %>1<% } else { %>"existing_id"<% } %>);
  <%_ } _%>
  <%_ if (dtoMapstruct) { _%>
        <%= dtoClass %> <%= dtoInstance %> = <%= entityInstance %>Mapper.toDto(<%= persistInstance %>);
  <%_ } _%>

        int databaseSizeBeforeCreate = <%= entityInstance %>Repository.findAll()<%= callListBlock %>.size();
  <%_ if (searchEngineElasticsearch) { _%>
        int searchDatabaseSizeBefore = IterableUtil.sizeOf(<%= entityInstance %>SearchRepository.findAll()<%= callListBlock %>);
  <%_ } _%>

        // An entity with an existing ID cannot be created, so this API call must fail
  <%_ if (reactive) { _%>
        webTestClient.post().uri(ENTITY_API_URL)
            .contentType(MediaType.APPLICATION_JSON)
            .bodyValue(TestUtil.convertObjectToJsonBytes(<%= restInstance %>))
            .exchange()
            .expectStatus().isBadRequest();
  <%_ } else { _%>
        rest<%= entityClass %>MockMvc.perform(post(ENTITY_API_URL)<% if (authenticationUsesCsrf) { %>.with(csrf())<% }%>
            .contentType(MediaType.APPLICATION_JSON)
            .content(TestUtil.convertObjectToJsonBytes(<%= restInstance %>)))
            .andExpect(status().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) { _%>
        int searchDatabaseSizeAfter = IterableUtil.sizeOf(<%= entityInstance %>SearchRepository.findAll()<%= callListBlock %>);
        assertThat(searchDatabaseSizeAfter).isEqualTo(searchDatabaseSizeBefore);
  <%_ } _%>
    }

  <%_ 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();
    <%_ if (searchEngineElasticsearch) { _%>
        int searchDatabaseSizeBefore = IterableUtil.sizeOf(<%= entityInstance %>SearchRepository.findAll()<%= callListBlock %>);
    <%_ } _%>
    <%_ 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) { _%>
        <%= relationship.otherEntity.persistClass %> <%= otherEntityName %> = <%= otherEntityNameCapitalized %>ResourceIT.create<% if (!relationship.otherEntityUser) { _%>Updated<%_ } %>Entity(<% if (databaseTypeSql && ormTool === 'hibernate') { %>em<% } %>);
          <%_ if (databaseTypeSql && !reactive && ormTool === 'hibernate') { _%>
        em.persist(<%= otherEntityName %>);
        em.flush();
          <%_ } _%>
        <%_ } _%>
        <%_ alreadyGeneratedEntities.push(otherEntityName) _%>
      <%_ } _%>
    <%_ break; } _%>

        // Load the <%= entityInstance %>
        <%= persistClass %> updated<%= persistClass %> = <%= entityInstance %>Repository.findById(<%= persistInstance %>.get<%= primaryKey.nameCapitalized %>())<%- reactive ? '.block()' : (javaVersion === '8' ? '.orElseThrow(() -> new NoSuchElementException("No value present"))' : '.orElseThrow()') %>;
        assertThat(updated<%= persistClass %>).isNotNull();
    <%_ if (databaseTypeSql && !reactive && ormTool === 'hibernate') { _%>
        // 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 (authenticationUsesCsrf) { %>.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) { _%>
        int searchDatabaseSizeAfter = IterableUtil.sizeOf(<%= entityInstance %>SearchRepository.findAll()<%= callListBlock %>);
        assertThat(searchDatabaseSizeAfter).isEqualTo(searchDatabaseSizeBefore);
    <%_ } _%>
    }
  <%_ } _%>
  <%_ for (field of fieldsToTest) { _%>
    <%_ 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();
        <%_ if (searchEngineElasticsearch) { _%>
        int searchDatabaseSizeBefore = IterableUtil.sizeOf(<%= entityInstance %>SearchRepository.findAll()<%= callListBlock %>);
        <%_ } _%>
        // set the field null
        <%= persistInstance %>.set<%= field.fieldInJavaBeanMethod %>(null);

        // Create the <%= entityClass %>, which fails.<% if (dtoMapstruct) { %>
        <%= dtoClass %> <%= dtoInstance %> = <%= entityInstance %>Mapper.toDto(<%= persistInstance %>);<% } %>


        <%_ if (reactive) { _%>
        webTestClient.post().uri(ENTITY_API_URL)
            .contentType(MediaType.APPLICATION_JSON)
            .bodyValue(TestUtil.convertObjectToJsonBytes(<%= restInstance %>))
            .exchange()
            .expectStatus().isBadRequest();
        <%_ } else { _%>
        rest<%= entityClass %>MockMvc.perform(post(ENTITY_API_URL)<% if (authenticationUsesCsrf) { %>.with(csrf())<% }%>
            .contentType(MediaType.APPLICATION_JSON)
            .content(TestUtil.convertObjectToJsonBytes(<%= restInstance %>)))
            .andExpect(status().isBadRequest());
        <%_ } _%>

        <%_ if (databaseTypeCouchbase) { _%>
        SecurityContextHolder.setContext(TestSecurityContextHolder.getContext());
        <%_ } _%>
        List<<%= persistClass %>> <%= entityInstance %>List = <%= entityInstance %>Repository.findAll()<%= callListBlock %>;
        assertThat(<%= entityInstance %>List).hasSize(databaseSizeBeforeTest);
        <%_ if (searchEngineElasticsearch) { _%>
        int searchDatabaseSizeAfter = IterableUtil.sizeOf(<%= entityInstance %>SearchRepository.findAll()<%= callListBlock %>);
        assertThat(searchDatabaseSizeAfter).isEqualTo(searchDatabaseSizeBefore);
        <%_ } _%>

    }
      <%_ } _%>
    <%_ } _%>
  <%_ } _%>
<%_ } _%>
<%_ if (!jpaMetamodelFiltering && reactive && paginationNo) { _%>

    @Test<%= transactionalAnnotation %>
    void getAll<%= entityClassPlural %>AsStream() {
        // Initialize the database
  <%_ if (!primaryKey.derived) { _%>
    <%_ for (field of primaryKey.fields.filter(f => !f.autoGenerateByRepository)) { _%>
        <%= persistInstance %>.set<%= field.fieldNameCapitalized %>(<%- this.getJavaValueGeneratorForType(field.fieldType) %>);
    <%_ } _%>
  <%_ } _%>
        <%= entityInstance %>Repository.save(<%= persistInstance %>)<%= callBlock %>;

        List<<%= persistClass %>> <%= 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 fieldsToTest) {
    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() %>);
      <%_ if (!field.options || !field.options.customWrapType) { _%>
        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 %>(<%- this.getJavaValueGeneratorForType(field.fieldType) %>);
  <%_ } _%>
<%_ } _%>
        <%= entityInstance %>Repository.<%= saveMethod %>(<%= persistInstance %>)<%= callBlock %>;

        // Get all the <%= entityInstance %>List
<%_ if (reactive) { _%>
        webTestClient.get().uri(ENTITY_API_URL + "?sort=<%= primaryKey.name %>,desc")
            .accept(MediaType.APPLICATION_JSON)
            .exchange()
            .expectStatus().isOk()
            .expectHeader().contentType(MediaType.APPLICATION_JSON)
            .expectBody()
<%_ } else { _%>
        rest<%= entityClass %>MockMvc.perform(get(ENTITY_API_URL<% if (!databaseTypeCassandra) { %> + "?sort=<%= primaryKey.name %>,desc"<% } %>))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
<%_ } _%>
<%_ if (databaseTypeSql || databaseTypeMongodb || databaseTypeCouchbase || databaseTypeCassandra) { _%>
            <%= !reactive ? '.andExpect(' : '.' %>jsonPath("$.[*].<%= primaryKey.name %>").value(hasItem(<%= idValue %>))<%= !reactive ? ')' : '' %><%_ } _%><% for (field of fieldsToTest) { %>
  <%_ if (field.fieldTypeBinary && !field.blobContentTypeText && (!field.options || !field.options.customWrapType)) { _%>
            <%= !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) { %><% if (field.options && field.options.customWrapType && field.options.customWrapType.indexOf('Array_') !== -1) { %>Arrays.toString(<% } else { %>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 (implementsEagerLoadApis && !databaseTypeNeo4j && !databaseTypeCouchbase) { %>
    @SuppressWarnings({"unchecked"})
    void getAll<%= entityClassPlural %>WithEagerRelationshipsIsEnabled() <% if (!reactive) { %>throws Exception <% } %>{
  <%_ if (!serviceNo) { _%>
        when(<%= entityInstance %>ServiceMock.<% if (ormTool === 'hibernate') { %>findAllWithEagerRelationships<% } else { %>findAll<% } %>(any())).thenReturn(<% if (reactive) { %>Flux.empty()<% } else { %><% if (ormTool === 'hibernate') { %>new PageImpl<% } else { %>new Page().setRecords<% } %>(new ArrayList<>())<% }%>);
  <%_ } else { _%>
        when(<%= entityInstance %>RepositoryMock.<% if (ormTool === 'hibernate') { %>findAllWithEagerRelationships(any())<% } else { %>selectPage(any(), any())<% } %>).thenReturn(<% if (reactive) { %>Flux.empty()<% } else { %><% if (ormTool === 'hibernate') { %>new PageImpl<% } else { %>new Page().setRecords<% } %>(new ArrayList<>())<% }%>);
  <%_ } _%>

  <%_ if (reactive) { _%>
        webTestClient.get().uri(ENTITY_API_URL + "?eagerload=true")
            .exchange()
            .expectStatus().isOk();
  <%_ } else { _%>
        rest<%= entityClass %>MockMvc.perform(get(ENTITY_API_URL + "?eagerload=true"))
            .andExpect(status().isOk());
  <%_ } _%>

  <%_ if (!serviceNo) { _%>
        verify(<%= entityInstance %>ServiceMock, times(1)).<% if (ormTool === 'hibernate') { %>findAllWithEagerRelationships<% } else { %>findAll<% } %>(any());
  <%_ } else { _%>
        verify(<%= entityInstance %>RepositoryMock, times(1)).<% if (ormTool === 'hibernate') { %>findAllWithEagerRelationships(any())<% } else { %>selectPage(any(), any())<% } %>;
  <%_ } _%>
    }

    @SuppressWarnings({"unchecked"})
    void getAll<%= entityClassPlural %>WithEagerRelationshipsIsNotEnabled() <% if (!reactive) { %>throws Exception <% } %>{
  <%_ if (!serviceNo) { _%>
        when(<%= entityInstance %>ServiceMock.<% if (ormTool === 'hibernate') { %>findAllWithEagerRelationships<% } else { %>findAll<% } %>(any())).thenReturn(<% if (reactive) { %>Flux.empty()<% } else { %><% if (ormTool === 'hibernate') { %>new PageImpl<% } else { %>new Page().setRecords<% } %>(new ArrayList<>())<% }%>);
  <%_ } else { _%>
        when(<%= entityInstance %>RepositoryMock.<% if (ormTool === 'hibernate') { %>findAllWithEagerRelationships(any())<% } else { %>selectPage(any(), any())<% } %>).thenReturn(<% if (reactive) { %>Flux.empty()<% } else { %>new PageImpl(new ArrayList<>())<% }%>);
  <%_ } _%>

  <%_ if (reactive) { _%>
        webTestClient.get().uri(ENTITY_API_URL + "?eagerload=false")
            .exchange()
            .expectStatus().isOk();
  <%_ } else { _%>
        rest<%= entityClass %>MockMvc.perform(get(ENTITY_API_URL + "?eagerload=false"))
            .andExpect(status().isOk());
  <%_ } _%>
        verify(<%= entityInstance %>RepositoryMock, times(1)).findAll<% if (reactive) { %>WithEagerRelationships(any()<% } else { %>(<% if (ormTool === 'hibernate') { %>any(Pageable.class)<% } %><% } %>);
    }
<%_ } _%>

    @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 %>(<%- this.getJavaValueGeneratorForType(field.fieldType) %>);
  <%_ } _%>
<%_ } _%>
        <%= entityInstance %>Repository.<%= saveMethod %>(<%= persistInstance %>)<%= callBlock %>;

        // Get the <%= entityInstance %>
<%_ if (reactive) { _%>
        webTestClient.get().uri(ENTITY_API_URL_ID, <%= persistInstance %>.get<%= primaryKey.nameCapitalized %>())
            .accept(MediaType.APPLICATION_JSON)
            .exchange()
            .expectStatus().isOk()
            .expectHeader().contentType(MediaType.APPLICATION_JSON)
            .expectBody()
<%_ } else { _%>
        rest<%= entityClass %>MockMvc.perform(get(ENTITY_API_URL_ID, <%= persistInstance %>.get<%= primaryKey.nameCapitalized %>()))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
<%_ } _%>
<%_ if (databaseTypeSql || databaseTypeMongodb || databaseTypeCouchbase || databaseTypeCassandra) { _%>
            <%= !reactive ? '.andExpect(' : '.' %>jsonPath("$.<%= primaryKey.name %>").value(<%= reactive ? 'is(' : '' %><%= idValue %>))<%_ } _%><% for (field of fieldsToTest) { %>
  <%_ if (field.fieldTypeBinary && !field.blobContentTypeText && (!field.options || !field.options.customWrapType)) { _%>
            <%= !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) { %><% if (field.options && field.options.customWrapType && field.options.customWrapType.indexOf('Array_') !== -1) { %>Arrays.toString(<% } else { %>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 || primaryKey.typeInteger) { _%>
        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);
  <%_ } _%>
    }

  <%_ fieldsToTest.forEach((searchBy) => { /* we can't filter by all the fields. */_%>
    <%_ if (searchBy.filterableField) { _%>

    @Test<%= transactionalAnnotation %>
    void getAll<%= entityClassPlural %>By<%= searchBy.fieldInJavaBeanMethod %>IsEqualToSomething() <% if (!reactive) { %>throws Exception <% } %>{
        // Initialize the database
        <%= entityInstance %>Repository.<%= saveMethod %>(<%= persistInstance %>)<%= callBlock %>;

        // Get all the <%= entityInstance %>List where <%= searchBy.fieldName %> equals to <%= 'DEFAULT_' + searchBy.fieldNameUnderscored.toUpperCase() %>
        default<%= entityClass %>ShouldBeFound("<%= searchBy.fieldName %>.equals=" + <%= 'DEFAULT_' + searchBy.fieldNameUnderscored.toUpperCase() %>);

        // Get all the <%= entityInstance %>List where <%= searchBy.fieldName %> equals to <%= 'UPDATED_' + searchBy.fieldNameUnderscored.toUpperCase() %>
        default<%= entityClass %>ShouldNotBeFound("<%= searchBy.fieldName %>.equals=" + <%= 'UPDATED_' + searchBy.fieldNameUnderscored.toUpperCase() %>);
    }

    @Test<%= transactionalAnnotation %>
    void getAll<%= entityClassPlural %>By<%= searchBy.fieldInJavaBeanMethod %>IsInShouldWork() <% if (!reactive) { %>throws Exception <% } %>{
        // Initialize the database
        <%= entityInstance %>Repository.<%= saveMethod %>(<%= persistInstance %>)<%= callBlock %>;

        // Get all the <%= entityInstance %>List where <%= searchBy.fieldName %> in <%= 'DEFAULT_' + searchBy.fieldNameUnderscored.toUpperCase() %> or <%= 'UPDATED_' + searchBy.fieldNameUnderscored.toUpperCase() %>
        default<%= entityClass %>ShouldBeFound("<%= searchBy.fieldName %>.in=" + <%= 'DEFAULT_' + searchBy.fieldNameUnderscored.toUpperCase() %> + "," + <%= 'UPDATED_' + searchBy.fieldNameUnderscored.toUpperCase() %>);

        // Get all the <%= entityInstance %>List where <%= searchBy.fieldName %> equals to <%= 'UPDATED_' + searchBy.fieldNameUnderscored.toUpperCase() %>
        default<%= entityClass %>ShouldNotBeFound("<%= searchBy.fieldName %>.in=" + <%= 'UPDATED_' + searchBy.fieldNameUnderscored.toUpperCase() %>);
    }

    @Test<%= transactionalAnnotation %>
    void getAll<%= entityClassPlural %>By<%= searchBy.fieldInJavaBeanMethod %>IsNullOrNotNull() <% if (!reactive) { %>throws Exception <% } %>{
        // Initialize the database
        <%= entityInstance %>Repository.<%= saveMethod %>(<%= persistInstance %>)<%= callBlock %>;

        // Get all the <%= entityInstance %>List where <%= searchBy.fieldName %> is not null
        default<%= entityClass %>ShouldBeFound("<%= searchBy.fieldName %>.specified=true");

        // Get all the <%= entityInstance %>List where <%= searchBy.fieldName %> is null
        default<%= entityClass %>ShouldNotBeFound("<%= searchBy.fieldName %>.specified=false");
    }
      <%_ } _%>
      <%_ if (searchBy.fieldTypeString) { _%>
    @Test<%= transactionalAnnotation %>
    void getAll<%= entityClassPlural %>By<%= searchBy.fieldInJavaBeanMethod %>ContainsSomething() <% if (!reactive) { %>throws Exception <% } %>{
        // Initialize the database
        <%= entityInstance %>Repository.<%= saveMethod %>(<%= persistInstance %>)<%= callBlock %>;

        // Get all the <%= entityInstance %>List where <%= searchBy.fieldName %> contains <%= 'DEFAULT_' + searchBy.fieldNameUnderscored.toUpperCase() %>
        default<%= entityClass %>ShouldBeFound("<%= searchBy.fieldName %>.contains=" + <%= 'DEFAULT_' + searchBy.fieldNameUnderscored.toUpperCase() %>);

        // Get all the <%= entityInstance %>List where <%= searchBy.fieldName %> contains <%= 'UPDATED_' + searchBy.fieldNameUnderscored.toUpperCase() %>
        default<%= entityClass %>ShouldNotBeFound("<%= searchBy.fieldName %>.contains=" + <%= 'UPDATED_' + searchBy.fieldNameUnderscored.toUpperCase() %>);
    }

    @Test<%= transactionalAnnotation %>
    void getAll<%= entityClassPlural %>By<%= searchBy.fieldInJavaBeanMethod %>NotContainsSomething() <% if (!reactive) { %>throws Exception <% } %>{
        // Initialize the database
        <%= entityInstance %>Repository.<%= saveMethod %>(<%= persistInstance %>)<%= callBlock %>;

        // Get all the <%= entityInstance %>List where <%= searchBy.fieldName %> does not contain <%= 'DEFAULT_' + searchBy.fieldNameUnderscored.toUpperCase() %>
        default<%= entityClass %>ShouldNotBeFound("<%= searchBy.fieldName %>.doesNotContain=" + <%= 'DEFAULT_' + searchBy.fieldNameUnderscored.toUpperCase() %>);

        // Get all the <%= entityInstance %>List where <%= searchBy.fieldName %> does not contain <%= 'UPDATED_' + searchBy.fieldNameUnderscored.toUpperCase() %>
        default<%= entityClass %>ShouldBeFound("<%= searchBy.fieldName %>.doesNotContain=" + <%= 'UPDATED_' + searchBy.fieldNameUnderscored.toUpperCase() %>);
    }

    <%_ }
    // the range criteria
    if (searchBy.fieldTypeNumeric || searchBy.fieldTypeDuration || searchBy.fieldTypeLocalDate || searchBy.fieldTypeZonedDateTime) {
      var defaultValue = 'DEFAULT_' + searchBy.fieldNameUnderscored.toUpperCase();
      var biggerValue = 'UPDATED_' + searchBy.fieldNameUnderscored.toUpperCase();
      var smallerValue = 'SMALLER_' + searchBy.fieldNameUnderscored.toUpperCase();
      if (searchBy.fieldValidate && searchBy.fieldValidationMax) {
          // if maximum is specified the updated variable is smaller than the default one!
        if (searchBy.fieldTypeBigDecimal) {
              biggerValue = '(' + defaultValue + '.add(BigDecimal.ONE))';
        } else if (searchBy.fieldTypeDuration || searchBy.fieldTypeLocalDate || searchBy.fieldTypeZonedDateTime) {
              biggerValue = '(' + defaultValue + '.plus(1, ChronoUnit.DAYS))';
        } else {
              biggerValue = '(' + defaultValue + ' + 1)';
        }
      }
    _%>

    @Test<%= transactionalAnnotation %>
    void getAll<%= entityClassPlural %>By<%= searchBy.fieldInJavaBeanMethod %>IsGreaterThanOrEqualToSomething() <% if (!reactive) { %>throws Exception <% } %>{
        // Initialize the database
        <%= entityInstance %>Repository.<%= saveMethod %>(<%= persistInstance %>)<%= callBlock %>;

        // Get all the <%= entityInstance %>List where <%= searchBy.fieldName %> is greater than or equal to <%= defaultValue %>
        default<%= entityClass %>ShouldBeFound("<%= searchBy.fieldName %>.greaterThanOrEqual=" + <%= defaultValue %>);

        // Get all the <%= entityInstance %>List where <%= searchBy.fieldName %> is greater than or equal to <%= biggerValue %>
        default<%= entityClass %>ShouldNotBeFound("<%= searchBy.fieldName %>.greaterThanOrEqual=" + <%= biggerValue %>);
    }

    @Test<%= transactionalAnnotation %>
    void getAll<%= entityClassPlural %>By<%= searchBy.fieldInJavaBeanMethod %>IsLessThanOrEqualToSomething() <% if (!reactive) { %>throws Exception <% } %>{
        // Initialize the database
        <%= entityInstance %>Repository.<%= saveMethod %>(<%= persistInstance %>)<%= callBlock %>;

        // Get all the <%= entityInstance %>List where <%= searchBy.fieldName %> is less than or equal to <%= defaultValue %>
        default<%= entityClass %>ShouldBeFound("<%= searchBy.fieldName %>.lessThanOrEqual=" + <%= defaultValue %>);

        // Get all the <%= entityInstance %>List where <%= searchBy.fieldName %> is less than or equal to <%= smallerValue %>
        default<%= entityClass %>ShouldNotBeFound("<%= searchBy.fieldName %>.lessThanOrEqual=" + <%= smallerValue %>);
    }

    @Test<%= transactionalAnnotation %>
    void getAll<%= entityClassPlural %>By<%= searchBy.fieldInJavaBeanMethod %>IsLessThanSomething() <% if (!reactive) { %>throws Exception <% } %>{
        // Initialize the database
        <%= entityInstance %>Repository.<%= saveMethod %>(<%= persistInstance %>)<%= callBlock %>;

        // Get all the <%= entityInstance %>List where <%= searchBy.fieldName %> is less than <%= defaultValue %>
        default<%= entityClass %>ShouldNotBeFound("<%= searchBy.fieldName %>.lessThan=" + <%= defaultValue %>);

        // Get all the <%= entityInstance %>List where <%= searchBy.fieldName %> is less than <%= biggerValue %>
        default<%= entityClass %>ShouldBeFound("<%= searchBy.fieldName %>.lessThan=" + <%= biggerValue %>);
    }

    @Test<%= transactionalAnnotation %>
    void getAll<%= entityClassPlural %>By<%= searchBy.fieldInJavaBeanMethod %>IsGreaterThanSomething() <% if (!reactive) { %>throws Exception <% } %>{
        // Initialize the database
        <%= entityInstance %>Repository.<%= saveMethod %>(<%= persistInstance %>)<%= callBlock %>;

        // Get all the <%= entityInstance %>List where <%= searchBy.fieldName %> is greater than <%= defaultValue %>
        default<%= entityClass %>ShouldNotBeFound("<%= searchBy.fieldName %>.greaterThan=" + <%= defaultValue %>);

        // Get all the <%= entityInstance %>List where <%= searchBy.fieldName %> is greater than <%= smallerValue %>
        default<%= entityClass %>ShouldBeFound("<%= searchBy.fieldName %>.greaterThan=" + <%= smallerValue %>);
    }

    <%_ } _%>
  <%_ }); _%>
  <%_ filterTestableRelationships.forEach((relationship) => { _%>
    <%_ if (!relationship.bcConfig || (!relationship.bcConfig.unidirectionSkip && !relationship.bcConfig.jhiExt)) {
      if (!(((applicationTypeMonolith || applicationTypeMicroservice) && multiModule && moduleName && moduleName !== relationship.otherEntity.moduleName) ||
      (applicationTypeMicroservice && !(relationship.otherEntity.applications.includes('*') || relationship.otherEntity.applications.includes(baseName))))
      ) {
    _%>

    @Test<%= transactionalAnnotation %>
    void getAll<%= entityClassPlural %>By<%= relationship.relationshipNameCapitalized %>IsEqualToSomething() <% if (!reactive) { %>throws Exception <% } %>{
    <%_ if ((relationship.relationshipValidate && relationship.relationshipOneToOne) || relationship.id) { _%>
        // Get already existing entity
        <%= relationship.otherEntity.persistClass %> <%= relationship.relationshipFieldName %> = <%= persistInstance %>.get<%= relationship.relationshipNameCapitalized %>();
    <%_ } else { _%>
      <%_ if (databaseTypeSql && !reactive) { _%>
        <%= relationship.otherEntity.persistClass %> <%= relationship.relationshipFieldName %><% if (ormTool === 'mybatis') { %>= <%= createEntityPrefix %><%= relationship.otherEntityNameCapitalized %>ResourceIT.createEntity(<% if (ormTool === 'hibernate') { %>em<% } %>)<% } %>;
        <%_ if (ormTool === 'hibernate') { _%>
        if (<% if (ormTool === 'hibernate') { %>TestUtil.findAll(em, <%= relationship.otherEntity.persistClass %>.class)<% } else { %><%= entityInstance %>Repository.findAll()<% } %>.isEmpty()) {
            <%= entityInstance %>Repository.<%= saveMethodName %>(<%= persistInstance %>);
            <%= relationship.relationshipFieldName %> = <%= createEntityPrefix %><%= relationship.otherEntityNameCapitalized %>ResourceIT.createEntity(<% if (ormTool === 'hibernate') { %>em<% } %>);
        } else {
            // <%= relationship.relationshipFieldName %> = <% if (ormTool === 'hibernate') { %>TestUtil.findAll(em, <%= relationship.otherEntity.persistClass %>.class)<% } else { %><%= relationship.otherEntity.entityInstance %>Repository.findAll()<% } %>.get(0);
            <%= relationship.relationshipFieldName %> = new <%= relationship.otherEntity.persistClass %>(); // todo
        }
        <%_ } _%>
      <%_ } else { _%>
        <%= relationship.otherEntity.persistClass %> <%= relationship.relationshipFieldName %> = <%= relationship.otherEntityNameCapitalized %>ResourceIT.createEntity(<% if (ormTool === 'hibernate') { %>em<% } %>);
      <%_ } _%>
      <%_ if(reactive) { _%>
        <%= relationship.otherEntity.persistInstance %>Repository.<%= saveMethod %>(<%= relationship.relationshipFieldName %>)<%= callBlock %>;
      <%_ } else { _%>
        <%_ if (ormTool === 'hibernate') { _%>
        em.persist(<%= relationship.relationshipFieldName %>);
        em.flush();
        <%_ } _%>
      <%_ } _%>
      <%_ if (!reactive && (relationship.relationshipManyToMany || relationship.relationshipOneToMany) && (!relationship.bcConfig || (relationship.bcConfig && !relationship.bcConfig.unidirectionSkip))) { _%>
        <%= ormTool === 'mybatis' ? '// ' : ''%><%= persistInstance %>.add<%= relationship.relationshipNameCapitalized %>(<%= relationship.relationshipFieldName %>);
      <%_ } else if (!reactive) { _%>
        <%_ if (!(relationship.relationshipTypeManyToOne && relationship.bcConfig && relationship.bcConfig.unidirectionSkip)) { _%>
            <%_ if (moduleName === relationship.otherEntity.moduleName || !multiModule) { _%>
        <%= persistInstance %>.set<%= relationship.relationshipNameCapitalized %>(<%= relationship.relationshipFieldName %>);
            <%_ } else { _%>
        <%= persistInstance %>.set<%= relationship.relationshipNameCapitalized %>Id(<%= relationship.relationshipFieldName %>.get<%= relationship.otherEntity.primaryKey.nameCapitalized %>());
                <%_ if (relationship.otherEntityFieldCapitalized) { _%>
        <%= persistInstance %>.set<%= relationship.relationshipNameCapitalized %><%= relationship.otherEntityFieldCapitalized %>(<%= relationship.relationshipFieldName %>.get<%= relationship.otherEntityFieldCapitalized %>());
                <%_ } _%>
            <%_ } _%>
        <%_ } _%>
        <%_ if (!relationship.ownerSide) { _%>
        <%= relationship.relationshipFieldName %>.set<%= relationship.otherEntityRelationshipNameCapitalized %>(<%= persistInstance %>);
        <%_ } _%>
      <%_ } else { _%>
        <%= relationship.otherEntity.primaryKey.type %> <%= relationship.relationshipFieldName %>Id = <%= relationship.relationshipFieldName %>.get<%= relationship.otherEntity.primaryKey.nameCapitalized %>();
        <%= persistInstance %>.set<%= relationship.relationshipNameCapitalized %>Id(<%= relationship.relationshipFieldName %>Id);
        <%= entityInstance %>Repository.<%= saveMethod %>(<%= persistInstance %>)<%= callBlock %>;
      <%_ } _%>
    <%_ } _%>
    <%_ if(!reactive) { _%>
        <%= entityInstance %>Repository.<%= saveMethodName %>(<%= persistInstance %>);
        <%= relationship.otherEntity.primaryKey.type %> <%= relationship.relationshipFieldName %>Id = <%= relationship.relationshipFieldName %>.get<%= relationship.otherEntity.primaryKey.nameCapitalized %>();
    <%_ } _%>
        // Get all the <%= entityInstance %>List where <%= relationship.relationshipFieldName %> equals to <%= relationship.relationshipFieldName %>Id
        default<%= entityClass %>ShouldBeFound("<%= relationship.relationshipFieldName %>Id.equals=" + <%= relationship.relationshipFieldName %>Id);

    <%_
    const initInvalidPrimaryKey = {
        'String' : '"invalid-id"',
        'Long' : '(' + relationship.relationshipFieldName + 'Id + 1)',
        'UUID' : 'UUID.randomUUID()'
    }[relationship.otherEntity.primaryKey.type];
    _%>
        // Get all the <%= entityInstance %>List where <%= relationship.relationshipFieldName %> equals to <%- initInvalidPrimaryKey %>
        default<%= entityClass %>ShouldNotBeFound("<%= relationship.relationshipFieldName %>Id.equals=" + <%- initInvalidPrimaryKey %>);
    }

  <%_ }}}); _%>
    /**
     * Executes the search, and checks that the default entity is returned.
     */
  <%_ if (reactive) { _%>
    private void default<%= entityClass %>ShouldBeFound(String filter) {
        webTestClient.get().uri(ENTITY_API_URL + "?sort=<%= primaryKey.name %>,desc&" + filter)
            .accept(MediaType.APPLICATION_JSON)
            .exchange()
            .expectStatus().isOk()
            .expectHeader().contentType(MediaType.APPLICATION_JSON)
            .expectBody()
            .jsonPath("$.[*].<%= primaryKey.name %>").value(hasItem(<%= idValue %>))<% for (field of fieldsToTest) { %>
      <%_ if (field.fieldTypeBinary && !field.blobContentTypeText && (!field.options || !field.options.customWrapType)) { _%>
            .jsonPath("$.[*].<%= field.fieldName %>ContentType").value(hasItem(<%= 'DEFAULT_' + field.fieldNameUnderscored.toUpperCase() %>_CONTENT_TYPE))
      <%_ } _%>
            .jsonPath("$.[*].<%= field.fieldName %>").value(hasItem(<% if
      (field.fieldTypeBinary && !field.blobContentTypeText) { %><% if (field.options && field.options.customWrapType && field.options.customWrapType.indexOf('Array_') !== -1) { %>Arrays.toString(<% } else { %>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()<% } %>))<%_ } _%>;

        // Check, that the count call also returns 1
        webTestClient.get().uri(ENTITY_API_URL + "/count?sort=<%= primaryKey.name %>,desc&" + filter)
                .accept(MediaType.APPLICATION_JSON)
                .exchange()
                .expectStatus().isOk()
                .expectHeader().contentType(MediaType.APPLICATION_JSON)
                .expectBody()
      <%_ if(reactive) { _%>
                .jsonPath("$")
                .value(is(1));
      <%_ } else { _%>
                .json("1");
      <%_ } _%>
    }
  <%_ } else { _%>
    private void default<%= entityClass %>ShouldBeFound(String filter) throws Exception {
        rest<%= entityClass %>MockMvc.perform(get(ENTITY_API_URL + "?sort=<%= primaryKey.name %>,desc&" + filter))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
            <%_
            const primaryKeyConversion = {
                'Long' : '.intValue()',
                'UUID' : '.toString()'
            }[primaryKey.type] || '';
            _%>
            .andExpect(jsonPath("$.[*].<%= primaryKey.name %>").value(hasItem(<%= persistInstance %>.get<%= primaryKey.nameCapitalized %>()<%= primaryKeyConversion %>)))<% fieldsToTest.forEach((field) => { %>
    <%_ if (field.fieldTypeBinary && !field.blobContentTypeText && (!field.options || !field.options.customWrapType)) { _%>
            .andExpect(jsonPath("$.[*].<%= field.fieldName %>ContentType").value(hasItem(<%= 'DEFAULT_' + field.fieldNameUnderscored.toUpperCase() %>_CONTENT_TYPE)))
    <%_ } _%>
            .andExpect(jsonPath("$.[*].<%= field.fieldName %>").value(hasItem(<%
    if (field.fieldTypeBinary && !field.blobContentTypeText) { %><% if (field.options && field.options.customWrapType && field.options.customWrapType.indexOf('Array_') !== -1) { %>Arrays.toString(<% } else { %>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()<% } %>)))<% }); %>;

        // Check, that the count call also returns 1
        rest<%= entityClass %>MockMvc.perform(get(ENTITY_API_URL + "/count?sort=<%= primaryKey.name %>,desc&" + filter))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
            .andExpect(content().string("1"));
    }
  <%_ } _%>

    /**
     * Executes the search, and checks that the default entity is not returned.
     */
  <%_ if (reactive) { _%>
    private void default<%= entityClass %>ShouldNotBeFound(String filter) {
        webTestClient.get().uri(ENTITY_API_URL + "?sort=<%= primaryKey.name %>,desc&" + filter)
            .accept(MediaType.APPLICATION_JSON)
            .exchange()
            .expectStatus().isOk()
            .expectHeader().contentType(MediaType.APPLICATION_JSON)
            .expectBody()
            .jsonPath("$").isArray()
            .jsonPath("$").isEmpty();

        // Check, that the count call also returns 0
        webTestClient.get().uri(ENTITY_API_URL + "/count?sort=<%= primaryKey.name %>,desc&" + filter)
            .accept(MediaType.APPLICATION_JSON)
            .exchange()
            .expectStatus().isOk()
            .expectHeader().contentType(MediaType.APPLICATION_JSON)
            .expectBody()
      <%_ if(reactive) { _%>
            .jsonPath("$")
            .value(is(0));
      <%_ } else { _%>
            .json("0");
      <%_ } _%>
    }
  <%_ } else { _%>
    private void default<%= entityClass %>ShouldNotBeFound(String filter) throws Exception {
        rest<%= entityClass %>MockMvc.perform(get(ENTITY_API_URL + "?sort=<%= primaryKey.name %>,desc&" + filter))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
            .andExpect(jsonPath("$").isArray())
            .andExpect(jsonPath("$").isEmpty());

        // Check, that the count call also returns 0
        rest<%= entityClass %>MockMvc.perform(get(ENTITY_API_URL + "/count?sort=<%= primaryKey.name %>,desc&" + filter))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
            .andExpect(content().string("0"));
    }
  <%_ } _%>

<%_  } _%>
    @Test<%= transactionalAnnotation %>
    void getNonExisting<%= entityClass %>() <% if (!reactive) { %>throws Exception <% } %>{
        // Get the <%= entityInstance %>
<%_ if (reactive) { _%>
        webTestClient.get().uri(ENTITY_API_URL_ID, <% if (primaryKey.typeInteger) { %>Integer.MAX_VALUE<% } else if (primaryKey.typeLong || primaryKey.typeString) { %>Long.MAX_VALUE<% } else if (primaryKey.typeUUID) { %>UUID.randomUUID().toString()<% } %>)
            .accept(MediaType.APPLICATION_PROBLEM_JSON)
            .exchange()
            .expectStatus().isNotFound();
<%_ } else { _%>
        rest<%= entityClass %>MockMvc.perform(get(ENTITY_API_URL_ID, <% if (primaryKey.typeInteger) { %>Integer.MAX_VALUE<% } else if (primaryKey.typeLong || primaryKey.typeString) { %>Long.MAX_VALUE<% } else if (primaryKey.typeUUID) { %>UUID.randomUUID().toString()<% } %>))
            .andExpect(status().isNotFound());
<%_ } _%>
    }
<%_ if (!readOnly) { _%>

    @Test<%= transactionalAnnotation %>
    void putExisting<%= entityClass %>() throws Exception {
        // Initialize the database
  <%_ if (!primaryKey.derived) { _%>
    <%_ for (field of primaryKey.fields.filter(f => !f.autoGenerateByRepository)) { _%>
        <%= persistInstance %>.set<%= field.fieldNameCapitalized %>(<%- this.getJavaValueGeneratorForType(field.fieldType) %>);
    <%_ } _%>
  <%_ } _%>
        <%= entityInstance %>Repository.<%= saveMethod %>(<%= persistInstance %>)<%= callBlock %>;

        int databaseSizeBeforeUpdate = <%= entityInstance %>Repository.findAll()<%= callListBlock %>.size();
  <%_ if (searchEngineElasticsearch) { _%>
        <%= entityInstance %>SearchRepository.save(<%= persistInstance %>)<%= callBlock %>;
        int searchDatabaseSizeBefore = IterableUtil.sizeOf(<%= entityInstance %>SearchRepository.findAll()<%= callListBlock %>);
  <%_ } _%>

        // Update the <%= entityInstance %>
        <%= persistClass %> updated<%= persistClass %> = <%= entityInstance %>Repository.findById(<%= persistInstance %>.get<%= primaryKey.nameCapitalized %>())<%- reactive ? '.block()' : (javaVersion === '8' ? '.orElseThrow(() -> new NoSuchElementException("No value present"))' : '.orElseThrow()') %>;
  <%_ if (databaseTypeSql && !reactive && ormTool === 'hibernate') { _%>
        // Disconnect from session so that the updates on updated<%= persistClass %> are not directly saved in db
        em.detach(updated<%= persistClass %>);
  <%_ } _%>
  <%_ if (fluentMethods && fieldsToTest.length > 0) { _%>
        updated<%= persistClass %><% for (field of fieldsToTest) { %>
            .<%= field.fieldName %>(<%= 'UPDATED_' + field.fieldNameUnderscored.toUpperCase() %>)<% if (field.fieldTypeBinary && !field.blobContentTypeText) { %>
            .<%= field.fieldName %>ContentType(<%= 'UPDATED_' + field.fieldNameUnderscored.toUpperCase() %>_CONTENT_TYPE)<% } %><% } %>;
  <%_ } else { _%>
    <%_ for (field of fieldsToTest) { _%>
        updated<%= persistClass %>.set<%= field.fieldInJavaBeanMethod %>(<%= 'UPDATED_' + field.fieldNameUnderscored.toUpperCase() %>);
      <%_ if (field.fieldTypeBinary && !field.blobContentTypeText && (!field.options || !field.options.customWrapType)) { _%>
        updated<%= persistClass %>.set<%= field.fieldInJavaBeanMethod %>ContentType(<%= 'UPDATED_' + field.fieldNameUnderscored.toUpperCase() %>_CONTENT_TYPE);
      <%_ } _%>
    <%_ } _%>
  <%_ } _%>
  <%_ if (dtoMapstruct) { _%>
        <%= dtoClass %> <%= dtoInstance %> = <%= entityInstance %>Mapper.toDto(updated<%= persistClass %>);
  <%_ } _%>

  <%_ if (reactive) { _%>
        webTestClient.put().uri(ENTITY_API_URL_ID, <%= (dtoMapstruct ? dtoInstance : 'updated' + persistClass) %>.get<%= primaryKey.nameCapitalized %>())
            .contentType(MediaType.APPLICATION_JSON)
            .bodyValue(TestUtil.convertObjectToJsonBytes(<%= (dtoMapstruct ? dtoInstance : 'updated' + persistClass) %>))
            .exchange()
            .expectStatus().isOk();
  <%_ } else { _%>
        rest<%= entityClass %>MockMvc.perform(put(ENTITY_API_URL_ID, <%= (dtoMapstruct ? dtoInstance : 'updated' + persistClass) %>.get<%= primaryKey.nameCapitalized %>())<% if (authenticationUsesCsrf) { %>.with(csrf())<% } %>
            .contentType(MediaType.APPLICATION_JSON)
            .content(TestUtil.convertObjectToJsonBytes(<%= (dtoMapstruct ? dtoInstance : '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(databaseSizeBeforeUpdate);
        <%= persistClass %> test<%= entityClass %> = <%= entityInstance %>List.get(<%= entityInstance %>List.size() - 1);
  <%_ for (const field of fieldsToTest) { _%>
    <%_ if (field.fieldTypeZonedDateTime) { _%>
        assertThat(test<%= entityClass %>.get<%= field.fieldInJavaBeanMethod %>()).isEqualTo(<%= 'UPDATED_' + field.fieldNameUnderscored.toUpperCase() %>);
    <%_ } else if (field.fieldTypeBinary && !field.blobContentTypeText) { _%>
        assertThat(test<%= entityClass %>.get<%= field.fieldInJavaBeanMethod %>()).isEqualTo(<%= 'UPDATED_' + field.fieldNameUnderscored.toUpperCase() %>);
        <%_ if (!field.options || !field.options.customWrapType) { _%>
        assertThat(test<%= entityClass %>.get<%= field.fieldInJavaBeanMethod %>ContentType()).isEqualTo(<%= 'UPDATED_' + field.fieldNameUnderscored.toUpperCase() %>_CONTENT_TYPE);
        <%_ } _%>
    <%_ } else { _%>
        assertThat(test<%= entityClass %>.get<%= field.fieldInJavaBeanMethod %>()).isEqualTo(<%= 'UPDATED_' + field.fieldNameUnderscored.toUpperCase() %>);
    <%_ } _%>
  <%_ } _%>
  <%_ if (searchEngineElasticsearch) { _%>
        await().atMost(5, TimeUnit.SECONDS).untilAsserted(() -> {
            int searchDatabaseSizeAfter = IterableUtil.sizeOf(<%= entityInstance %>SearchRepository.findAll()<%= callListBlock %>);
            assertThat(searchDatabaseSizeAfter).isEqualTo(searchDatabaseSizeBefore);
            List<<%= persistClass %>> <%= entityInstance %>SearchList = IterableUtils.toList(<%= entityInstance %>SearchRepository.findAll()<%= callListBlock %>);
        <%= persistClass %> test<%= entityClass %>Search = <%= entityInstance %>SearchList.get(searchDatabaseSizeAfter - 1);
    <%_ for (const field of fieldsToTest) { _%>
      <%_ if (field.fieldTypeZonedDateTime) { _%>
            assertThat(test<%= entityClass %>Search.get<%= field.fieldInJavaBeanMethod %>()).isEqualTo(<%= 'UPDATED_' + field.fieldNameUnderscored.toUpperCase() %>);
      <%_ } else if (field.fieldTypeBinary && !field.blobContentTypeText) { _%>
            assertThat(test<%= entityClass %>Search.get<%= field.fieldInJavaBeanMethod %>()).isEqualTo(<%= 'UPDATED_' + field.fieldNameUnderscored.toUpperCase() %>);
            assertThat(test<%= entityClass %>Search.get<%= field.fieldInJavaBeanMethod %>ContentType()).isEqualTo(<%= 'UPDATED_' + field.fieldNameUnderscored.toUpperCase() %>_CONTENT_TYPE);
      <%_ } else if (field.fieldTypeBigDecimal) { _%>
            assertThat(test<%= entityClass %>Search.get<%= field.fieldInJavaBeanMethod %>()).isEqualByComparingTo(<%= 'UPDATED_' + field.fieldNameUnderscored.toUpperCase() %>);
      <%_ } else { _%>
            assertThat(test<%= entityClass %>Search.get<%= field.fieldInJavaBeanMethod %>()).isEqualTo(<%= 'UPDATED_' + field.fieldNameUnderscored.toUpperCase() %>);
      <%_ } _%>
    <%_ } _%>
      });
  <%_ } _%>
    }

    @Test<%= transactionalAnnotation %>
    void putNonExisting<%= entityClass %>() throws Exception {
        int databaseSizeBeforeUpdate = <%= entityInstance %>Repository.findAll()<%= callListBlock %>.size();
  <%_ if (searchEngineElasticsearch) { _%>
        int searchDatabaseSizeBefore = IterableUtil.sizeOf(<%= entityInstance %>SearchRepository.findAll()<%= callListBlock %>);
  <%_ } _%>
        <%= persistInstance %>.set<%= primaryKey.nameCapitalized %>(<%- this.getJavaValueGeneratorForType(primaryKey.type) %>);

  <%_ if (dtoMapstruct) { _%>
        // Create the <%= entityClass %>
        <%= dtoClass %> <%= dtoInstance %> = <%= entityInstance %>Mapper.toDto(<%= persistInstance %>);

  <%_ } _%>
        // If the entity doesn't have an ID, it will throw BadRequestAlertException
  <%_ if (reactive) { _%>
        webTestClient.put().uri(ENTITY_API_URL_ID, <%= restInstance %>.get<%= primaryKey.nameCapitalized %>())
            .contentType(MediaType.APPLICATION_JSON)
            .bodyValue(TestUtil.convertObjectToJsonBytes(<%= restInstance %>))
            .exchange()
            .expectStatus().isBadRequest();
  <%_ } else { _%>
        rest<%= entityClass %>MockMvc.perform(put(ENTITY_API_URL_ID, <%= restInstance %>.get<%= primaryKey.nameCapitalized %>())<% if (authenticationUsesCsrf) { %>.with(csrf())<% }%>
            .contentType(MediaType.APPLICATION_JSON)
            .content(TestUtil.convertObjectToJsonBytes(<%= restInstance %>)))
            .andExpect(status().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(databaseSizeBeforeUpdate);
  <%_ if (searchEngineElasticsearch) { _%>
        int searchDatabaseSizeAfter = IterableUtil.sizeOf(<%= entityInstance %>SearchRepository.findAll()<%= callListBlock %>);
        assertThat(searchDatabaseSizeAfter).isEqualTo(searchDatabaseSizeBefore);

  <%_ } _%>
    }

    @Test<%= transactionalAnnotation %>
    void putWithIdMismatch<%= entityClass %>() throws Exception {
        int databaseSizeBeforeUpdate = <%= entityInstance %>Repository.findAll()<%= callListBlock %>.size();
  <%_ if (searchEngineElasticsearch) { _%>
        int searchDatabaseSizeBefore = IterableUtil.sizeOf(<%= entityInstance %>SearchRepository.findAll()<%= callListBlock %>);
  <%_ } _%>
        <%= persistInstance %>.set<%= primaryKey.nameCapitalized %>(<%- this.getJavaValueGeneratorForType(primaryKey.type) %>);

  <%_ if (dtoMapstruct) { _%>
        // Create the <%= entityClass %>
        <%= dtoClass %> <%= dtoInstance %> = <%= entityInstance %>Mapper.toDto(<%= persistInstance %>);

  <%_ } _%>
        // If url ID doesn't match entity ID, it will throw BadRequestAlertException
  <%_ if (reactive) { _%>
        webTestClient.put().uri(ENTITY_API_URL_ID, <%- this.getJavaValueGeneratorForType(primaryKey.type) %>)
            .contentType(MediaType.APPLICATION_JSON)
            .bodyValue(TestUtil.convertObjectToJsonBytes(<%= restInstance %>))
            .exchange()
            .expectStatus().isBadRequest();
  <%_ } else { _%>
        rest<%= entityClass %>MockMvc.perform(put(ENTITY_API_URL_ID, <%- this.getJavaValueGeneratorForType(primaryKey.type) %>)<% if (authenticationUsesCsrf) { %>.with(csrf())<% } %>
            .contentType(MediaType.APPLICATION_JSON)
            .content(TestUtil.convertObjectToJsonBytes(<%= restInstance %>)))
            .andExpect(status().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(databaseSizeBeforeUpdate);
  <%_ if (searchEngineElasticsearch) { _%>
        int searchDatabaseSizeAfter = IterableUtil.sizeOf(<%= entityInstance %>SearchRepository.findAll()<%= callListBlock %>);
        assertThat(searchDatabaseSizeAfter).isEqualTo(searchDatabaseSizeBefore);
  <%_ } _%>
    }

    @Test<%= transactionalAnnotation %>
    void putWithMissingIdPathParam<%= entityClass %>() throws Exception {
        int databaseSizeBeforeUpdate = <%= entityInstance %>Repository.findAll()<%= callListBlock %>.size();
  <%_ if (searchEngineElasticsearch) { _%>
        int searchDatabaseSizeBefore = IterableUtil.sizeOf(<%= entityInstance %>SearchRepository.findAll()<%= callListBlock %>);
  <%_ } _%>
        <%= persistInstance %>.set<%= primaryKey.nameCapitalized %>(<%- this.getJavaValueGeneratorForType(primaryKey.type) %>);

  <%_ if (dtoMapstruct) { _%>
        // Create the <%= entityClass %>
        <%= dtoClass %> <%= dtoInstance %> = <%= entityInstance %>Mapper.toDto(<%= persistInstance %>);

  <%_ } _%>
        // If url ID doesn't match entity ID, it will throw BadRequestAlertException
  <%_ if (reactive) { _%>
        webTestClient.put().uri(ENTITY_API_URL)
            .contentType(MediaType.APPLICATION_JSON)
            .bodyValue(TestUtil.convertObjectToJsonBytes(<%= restInstance %>))
            .exchange()
            .expectStatus().isEqualTo(405);
  <%_ } else { _%>
        rest<%= entityClass %>MockMvc.perform(put(ENTITY_API_URL)<% if (authenticationUsesCsrf) { %>.with(csrf())<% } %>
            .contentType(MediaType.APPLICATION_JSON)
            .content(TestUtil.convertObjectToJsonBytes(<%= restInstance %>)))
            .andExpect(status().isMethodNotAllowed());
  <%_ } _%>

        // Validate the <%= entityClass %> in the database
  <%_ if (databaseTypeCouchbase) { _%>
        SecurityContextHolder.setContext(TestSecurityContextHolder.getContext());
  <%_ } _%>
        List<<%= persistClass %>> <%= entityInstance %>List = <%= entityInstance %>Repository.findAll()<%= callListBlock %>;
        assertThat(<%= entityInstance %>List).hasSize(databaseSizeBeforeUpdate);
  <%_ if (searchEngineElasticsearch) { _%>
        int searchDatabaseSizeAfter = IterableUtil.sizeOf(<%= entityInstance %>SearchRepository.findAll()<%= callListBlock %>);
        assertThat(searchDatabaseSizeAfter).isEqualTo(searchDatabaseSizeBefore);
  <%_ } _%>
    }

  <%_
    const prepareFieldForPatchTest = (field, includeCb) => {
      const includeField = includeCb();
      const fieldNameUnderscoreUppercased = field.fieldNameUnderscored.toUpperCase();
      const updateWithValue = includeField ? `UPDATED_${fieldNameUnderscoreUppercased}` : 'null';
      const testWithConstant = includeField ? `UPDATED_${fieldNameUnderscoreUppercased}` : `DEFAULT_${fieldNameUnderscoreUppercased}`;
      return { includeField, updateWithValue, testWithConstant, ...field};
    };
  _%>
    @Test<%= transactionalAnnotation %>
    void partialUpdate<%= entityClass %>WithPatch() throws Exception {
        // Initialize the database
  <%_ if (!primaryKey.derived) { _%>
    <%_ for (field of primaryKey.fields.filter(f => !f.autoGenerateByRepository)) { _%>
        <%= persistInstance %>.set<%= field.fieldNameCapitalized %>(<%- this.getJavaValueGeneratorForType(field.fieldType) %>);
    <%_ } _%>
  <%_ } _%>
        <%= entityInstance %>Repository.<%= saveMethod %>(<%= persistInstance %>)<%= callBlock %>;

  <%_ const fieldsToIncludeInPartialPatchTest = fieldsToTest.map(field => prepareFieldForPatchTest(field, () => faker.datatype.boolean())); _%>
<%- include('/_global_partials_entity_/it_patch_update.partial.java.ejs', {fields: fieldsToIncludeInPartialPatchTest, saveMethod, callBlock, callListBlock}); -%>
    }

    @Test<%= transactionalAnnotation %>
    void fullUpdate<%= entityClass %>WithPatch() throws Exception {
        // Initialize the database
  <%_ if (!primaryKey.derived) { _%>
    <%_ for (field of primaryKey.fields.filter(f => !f.autoGenerateByRepository)) { _%>
        <%= persistInstance %>.set<%= field.fieldNameCapitalized %>(<%- this.getJavaValueGeneratorForType(field.fieldType) %>);
    <%_ } _%>
  <%_ } _%>
        <%= entityInstance %>Repository.<%= saveMethod %>(<%= persistInstance %>)<%= callBlock %>;

  <% const fieldsToIncludeInFullPatchTest = fieldsToTest.map(field => prepareFieldForPatchTest(field, () => true)); %>
<%- include('/_global_partials_entity_/it_patch_update.partial.java.ejs', {fields: fieldsToIncludeInFullPatchTest, saveMethod, callBlock, callListBlock}); -%>
    }

    @Test<%= transactionalAnnotation %>
    void patchNonExisting<%= entityClass %>() throws Exception {
        int databaseSizeBeforeUpdate = <%= entityInstance %>Repository.findAll()<%= callListBlock %>.size();
  <%_ if (searchEngineElasticsearch) { _%>
        int searchDatabaseSizeBefore = IterableUtil.sizeOf(<%= entityInstance %>SearchRepository.findAll()<%= callListBlock %>);
  <%_ } _%>
        <%= persistInstance %>.set<%= primaryKey.nameCapitalized %>(<%- this.getJavaValueGeneratorForType(primaryKey.type) %>);

  <%_ if (dtoMapstruct) { _%>
            // Create the <%= entityClass %>
            <%= dtoClass %> <%= dtoInstance %> = <%= entityInstance %>Mapper.toDto(<%= persistInstance %>);

  <%_ } _%>
        // If the entity doesn't have an ID, it will throw BadRequestAlertException
  <%_ if (reactive) { _%>
        webTestClient.patch().uri(ENTITY_API_URL_ID, <%= restInstance %>.get<%= primaryKey.nameCapitalized %>())
            .contentType(MediaType.valueOf("application/merge-patch+json"))
            .bodyValue(TestUtil.convertObjectToJsonBytes(<%= restInstance %>))
            .exchange()
            .expectStatus().isBadRequest();
  <%_ } else { _%>
        rest<%= entityClass %>MockMvc.perform(patch(ENTITY_API_URL_ID, <%= restInstance %>.get<%= primaryKey.nameCapitalized %>())<% if (authenticationUsesCsrf) { %>.with(csrf())<% }%>
            .contentType("application/merge-patch+json")
            .content(TestUtil.convertObjectToJsonBytes(<%= restInstance %>)))
            .andExpect(status().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(databaseSizeBeforeUpdate);
  <%_ if (searchEngineElasticsearch) { _%>
    int searchDatabaseSizeAfter = IterableUtil.sizeOf(<%= entityInstance %>SearchRepository.findAll()<%= callListBlock %>);
    assertThat(searchDatabaseSizeAfter).isEqualTo(searchDatabaseSizeBefore);
  <%_ } _%>
    }

    @Test<%= transactionalAnnotation %>
    void patchWithIdMismatch<%= entityClass %>() throws Exception {
        int databaseSizeBeforeUpdate = <%= entityInstance %>Repository.findAll()<%= callListBlock %>.size();
  <%_ if (searchEngineElasticsearch) { _%>
        int searchDatabaseSizeBefore = IterableUtil.sizeOf(<%= entityInstance %>SearchRepository.findAll()<%= callListBlock %>);
  <%_ } _%>
        <%= persistInstance %>.set<%= primaryKey.nameCapitalized %>(<%- this.getJavaValueGeneratorForType(primaryKey.type) %>);

  <%_ if (dtoMapstruct) { _%>
            // Create the <%= entityClass %>
            <%= dtoClass %> <%= dtoInstance %> = <%= entityInstance %>Mapper.toDto(<%= persistInstance %>);

  <%_ } _%>
        // If url ID doesn't match entity ID, it will throw BadRequestAlertException
  <%_ if (reactive) { _%>
        webTestClient.patch().uri(ENTITY_API_URL_ID, <%- this.getJavaValueGeneratorForType(primaryKey.type) %>)
            .contentType(MediaType.valueOf("application/merge-patch+json"))
            .bodyValue(TestUtil.convertObjectToJsonBytes(<%= restInstance %>))
            .exchange()
            .expectStatus().isBadRequest();
  <%_ } else { _%>
        rest<%= entityClass %>MockMvc.perform(patch(ENTITY_API_URL_ID, <%- this.getJavaValueGeneratorForType(primaryKey.type) %>)<% if (authenticationUsesCsrf) { %>.with(csrf())<% } %>
            .contentType("application/merge-patch+json")
            .content(TestUtil.convertObjectToJsonBytes(<%= restInstance %>)))
            .andExpect(status().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(databaseSizeBeforeUpdate);
  <%_ if (searchEngineElasticsearch) { _%>
        int searchDatabaseSizeAfter = IterableUtil.sizeOf(<%= entityInstance %>SearchRepository.findAll()<%= callListBlock %>);
        assertThat(searchDatabaseSizeAfter).isEqualTo(searchDatabaseSizeBefore);
  <%_ } _%>
    }

    @Test<%= transactionalAnnotation %>
    void patchWithMissingIdPathParam<%= entityClass %>() throws Exception {
        int databaseSizeBeforeUpdate = <%= entityInstance %>Repository.findAll()<%= callListBlock %>.size();
  <%_ if (searchEngineElasticsearch) { _%>
      int searchDatabaseSizeBefore = IterableUtil.sizeOf(<%= entityInstance %>SearchRepository.findAll()<%= callListBlock %>);
  <%_ } _%>
        <%= persistInstance %>.set<%= primaryKey.nameCapitalized %>(<%- this.getJavaValueGeneratorForType(primaryKey.type) %>);

  <%_ if (dtoMapstruct) { _%>
            // Create the <%= entityClass %>
            <%= dtoClass %> <%= dtoInstance %> = <%= entityInstance %>Mapper.toDto(<%= persistInstance %>);

  <%_ } _%>
        // If url ID doesn't match entity ID, it will throw BadRequestAlertException
  <%_ if (reactive) { _%>
        webTestClient.patch().uri(ENTITY_API_URL)
            .contentType(MediaType.valueOf("application/merge-patch+json"))
            .bodyValue(TestUtil.convertObjectToJsonBytes(<%= restInstance %>))
            .exchange()
            .expectStatus().isEqualTo(405);
  <%_ } else { _%>
        rest<%= entityClass %>MockMvc.perform(patch(ENTITY_API_URL)<% if (authenticationUsesCsrf) { %>.with(csrf())<% } %>
            .contentType("application/merge-patch+json")
            .content(TestUtil.convertObjectToJsonBytes(<%= restInstance %>)))
            .andExpect(status().isMethodNotAllowed());
  <%_ } _%>

        // Validate the <%= entityClass %> in the database
  <%_ if (databaseTypeCouchbase) { _%>
        SecurityContextHolder.setContext(TestSecurityContextHolder.getContext());
  <%_ } _%>
        List<<%= persistClass %>> <%= entityInstance %>List = <%= entityInstance %>Repository.findAll()<%= callListBlock %>;
        assertThat(<%= entityInstance %>List).hasSize(databaseSizeBeforeUpdate);
  <%_ if (searchEngineElasticsearch) { _%>
        int searchDatabaseSizeAfter = IterableUtil.sizeOf(<%= entityInstance %>SearchRepository.findAll()<%= callListBlock %>);
        assertThat(searchDatabaseSizeAfter).isEqualTo(searchDatabaseSizeBefore);
  <%_ } _%>

    }

    @Test<%= transactionalAnnotation %>
    void delete<%= entityClass %>() <% if (!reactive) { %>throws Exception <% } %>{
        // Initialize the database
  <%_ if (!primaryKey.derived) { _%>
    <%_ for (field of primaryKey.fields.filter(f => !f.autoGenerateByRepository)) { _%>
        <%= persistInstance %>.set<%= primaryKey.nameCapitalized %>(<%- this.getJavaValueGeneratorForType(field.fieldType) %>);
    <%_ } _%>
  <%_ } _%>
        <%= entityInstance %>Repository.<%= saveMethod %>(<%= persistInstance %>)<%= callBlock %>;
  <%_ if (searchEngineElasticsearch) { _%>
        <%= entityInstance %>Repository.save(<%= persistInstance %>)<%= callBlock %>;
        <%= entityInstance %>SearchRepository.save(<%= persistInstance %>)<%= callBlock %>;
  <%_ } _%>

        int databaseSizeBeforeDelete = <%= entityInstance %>Repository.findAll()<%= callListBlock %>.size();
  <%_ if (searchEngineElasticsearch) { _%>
        int searchDatabaseSizeBefore = IterableUtil.sizeOf(<%= entityInstance %>SearchRepository.findAll()<%= callListBlock %>);
        assertThat(searchDatabaseSizeBefore).isEqualTo(databaseSizeBeforeDelete);
  <%_ } _%>

        // Delete the <%= entityInstance %>
  <%_ if (reactive) { _%>
        webTestClient.delete().uri(ENTITY_API_URL_ID, <%= persistInstance %>.get<%= primaryKey.nameCapitalized %>())
            .accept(MediaType.APPLICATION_JSON)
            .exchange()
            .expectStatus().isNoContent();
  <%_ } else { _%>
        rest<%= entityClass %>MockMvc.perform(delete(ENTITY_API_URL_ID, <%= persistInstance %>.get<%= primaryKey.nameCapitalized %>()<% if (primaryKey.typeUUID && databaseTypeSql) { %>.toString()<% } %>)<% if (authenticationUsesCsrf) { %>.with(csrf())<% }%>
            .accept(MediaType.APPLICATION_JSON))
            .andExpect(status().isNoContent());
  <%_ } _%>

        // Validate the database contains one less item
  <%_ if (databaseTypeCouchbase) { _%>
        SecurityContextHolder.setContext(TestSecurityContextHolder.getContext());
  <%_ } _%>
        List<<%= persistClass %>> <%= entityInstance %>List = <%= entityInstance %>Repository.findAll()<%= callListBlock %>;
        assertThat(<%= entityInstance %>List).hasSize(databaseSizeBeforeDelete - 1);
  <%_ if (searchEngineElasticsearch) { _%>
        int searchDatabaseSizeAfter = IterableUtil.sizeOf(<%= entityInstance %>SearchRepository.findAll()<%= callListBlock %>);
        assertThat(searchDatabaseSizeAfter).isEqualTo(searchDatabaseSizeBefore-1);
  <%_ } _%>

    }
<%_ } _%>
<%_ if (searchEngineAny) { _%>

  <%_ if (searchEngineCouchbase) { _%>
    @Timeout(value = 15, unit = TimeUnit.MINUTES)
  <%_ } _%>
    @Test<%= transactionalAnnotation %>
    void search<%= entityClass %>() <% if (!reactive) { %>throws Exception <% } %>{
        // Initialize the database
  <%_ if (!primaryKey.derived) { _%>
    <%_ for (field of primaryKey.fields.filter(f => !f.autoGenerateByRepository)) { _%>
        <%= persistInstance %>.set<%= field.fieldNameCapitalized %>(<%- this.getJavaValueGeneratorForType(field.fieldType) %>);
    <%_ } _%>
  <%_ } _%>
        <% if (ormTool === 'hibernate') { %><%= persistInstance %> = <% } %><%= entityInstance %>Repository.<%= saveMethod %>(<%= persistInstance %>)<%= callBlock %>;
  <%_ if (searchEngineElasticsearch) { _%>
        <%= entityInstance %>SearchRepository.save(<%= persistInstance %>)<%= callBlock %>;
  <%_ } else if (searchEngineCouchbase) { _%>
        // Wait for the <%= entityInstance %> to be indexed
        TestUtil.retryUntilNotEmpty(() -> <%= entityInstance %>Repository.search("id:" + <%= entityInstance %>.get<%= primaryKey.nameCapitalized %>())<% if (reactive) { %>.collectList().block()<% } %>);
  <%_ } _%>

        // Search the <%= entityInstance %>
  <%_ if (reactive) { _%>
        webTestClient.get().uri(ENTITY_SEARCH_API_URL + "?query=id:" + <%= persistInstance %>.get<%= primaryKey.nameCapitalized %>())
            .exchange()
            .expectStatus().isOk()
            .expectHeader().contentType(MediaType.APPLICATION_JSON)
            .expectBody()
  <%_ } else { _%>
        rest<%= entityClass %>MockMvc.perform(get(ENTITY_SEARCH_API_URL + "?query=id:" + <%= persistInstance %>.get<%= primaryKey.nameCapitalized %>()))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
  <%_ } _%>
  <%_ if (databaseTypeSql || databaseTypeMongodb || databaseTypeCouchbase || databaseTypeCassandra) { _%>
            <%= !reactive ? '.andExpect(' : '.' %>jsonPath("$.[*].<%= primaryKey.name %>").value(hasItem(<%= idValue %>))<%= !reactive ? ')' : '' %><%_ } _%><% for (field of fieldsToTest) { %>
  <%_ if (field.fieldTypeBinary && !field.blobContentTypeText && (!field.options || !field.options.customWrapType)) { _%>
            <%= !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) { %><% if (field.options && field.options.customWrapType && field.options.customWrapType.indexOf('Array_') !== -1) { %>Arrays.toString(<% } else { %>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 ? ')' : '' %><%_ } _%>;
    }
<%_ } _%>
}
