From 0fd30a57002242989b559c7d4a69b2bc06b43e81 Mon Sep 17 00:00:00 2001
From: Michael Hoennig <michael@hoennig.de>
Date: Mon, 29 Apr 2019 09:39:08 +0200
Subject: [PATCH] adding AccessMappings SepaMandateDTO with tests +
 consequences (HOWTO)

---
 .../hsadminng/domain/SepaMandate.java         |   6 +
 .../hsadminng/service/SepaMandateService.java |   2 +-
 .../hsadminng/service/dto/SepaMandateDTO.java |  42 +++-
 .../service/dto/SepaMandateDTOIntTest.java    | 189 ++++++++++++++++++
 .../service/dto/SepaMandateDTOUnitTest.java   |  96 +++++++++
 .../web/rest/SepaMandateResourceIntTest.java  |  37 ++--
 .../web/rest/SepaMandateResourceUnitTest.java |  56 ++++++
 7 files changed, 405 insertions(+), 23 deletions(-)
 create mode 100644 src/test/java/org/hostsharing/hsadminng/service/dto/SepaMandateDTOIntTest.java
 create mode 100644 src/test/java/org/hostsharing/hsadminng/service/dto/SepaMandateDTOUnitTest.java
 create mode 100644 src/test/java/org/hostsharing/hsadminng/web/rest/SepaMandateResourceUnitTest.java

diff --git a/src/main/java/org/hostsharing/hsadminng/domain/SepaMandate.java b/src/main/java/org/hostsharing/hsadminng/domain/SepaMandate.java
index 6edc6e09..bff9b4bf 100644
--- a/src/main/java/org/hostsharing/hsadminng/domain/SepaMandate.java
+++ b/src/main/java/org/hostsharing/hsadminng/domain/SepaMandate.java
@@ -64,10 +64,16 @@ public class SepaMandate implements Serializable {
     private Customer customer;
 
     // jhipster-needle-entity-add-field - JHipster will add fields here, do not remove
+
     public Long getId() {
         return id;
     }
 
+    public SepaMandate id(final Long id) {
+        this.id = id;
+        return this;
+    }
+
     public void setId(Long id) {
         this.id = id;
     }
diff --git a/src/main/java/org/hostsharing/hsadminng/service/SepaMandateService.java b/src/main/java/org/hostsharing/hsadminng/service/SepaMandateService.java
index 0e803e94..dc954647 100644
--- a/src/main/java/org/hostsharing/hsadminng/service/SepaMandateService.java
+++ b/src/main/java/org/hostsharing/hsadminng/service/SepaMandateService.java
@@ -18,7 +18,7 @@ import java.util.Optional;
  */
 @Service
 @Transactional
-public class SepaMandateService {
+public class SepaMandateService implements IdToDtoResolver<SepaMandateDTO> {
 
     private final Logger log = LoggerFactory.getLogger(SepaMandateService.class);
 
diff --git a/src/main/java/org/hostsharing/hsadminng/service/dto/SepaMandateDTO.java b/src/main/java/org/hostsharing/hsadminng/service/dto/SepaMandateDTO.java
index 914b22b9..7bf86a89 100644
--- a/src/main/java/org/hostsharing/hsadminng/service/dto/SepaMandateDTO.java
+++ b/src/main/java/org/hostsharing/hsadminng/service/dto/SepaMandateDTO.java
@@ -1,46 +1,64 @@
 package org.hostsharing.hsadminng.service.dto;
 
+import org.hostsharing.hsadminng.service.CustomerService;
+import org.hostsharing.hsadminng.service.SepaMandateService;
+import org.hostsharing.hsadminng.service.accessfilter.*;
+import org.springframework.boot.jackson.JsonComponent;
+import org.springframework.context.ApplicationContext;
+
 import javax.validation.constraints.NotNull;
 import javax.validation.constraints.Size;
-import java.io.Serializable;
 import java.time.LocalDate;
 import java.util.Objects;
 
 /**
  * A DTO for the SepaMandate entity.
  */
-public class SepaMandateDTO implements Serializable {
+public class SepaMandateDTO implements AccessMappings, FluentBuilder<SepaMandateDTO> {
 
+    @SelfId(resolver = SepaMandateService.class)
+    @AccessFor(read = {Role.CONTRACTUAL_CONTACT, Role.FINANCIAL_CONTACT})
     private Long id;
 
     @NotNull
     @Size(max = 40)
+    @AccessFor(init = {Role.CONTRACTUAL_CONTACT, Role.FINANCIAL_CONTACT}, read = {Role.CONTRACTUAL_CONTACT, Role.FINANCIAL_CONTACT})
     private String reference;
 
     @Size(max = 34)
+    @AccessFor(init = {Role.CONTRACTUAL_CONTACT, Role.FINANCIAL_CONTACT}, read = {Role.CONTRACTUAL_CONTACT, Role.FINANCIAL_CONTACT})
     private String iban;
 
     @Size(max = 11)
+    @AccessFor(init = {Role.CONTRACTUAL_CONTACT, Role.FINANCIAL_CONTACT}, read = {Role.CONTRACTUAL_CONTACT, Role.FINANCIAL_CONTACT})
     private String bic;
 
     @NotNull
+    @AccessFor(init = {Role.CONTRACTUAL_CONTACT, Role.FINANCIAL_CONTACT}, read = {Role.CONTRACTUAL_CONTACT, Role.FINANCIAL_CONTACT})
     private LocalDate grantingDocumentDate;
 
+    @AccessFor(init = Role.ADMIN, update = {Role.CONTRACTUAL_CONTACT, Role.FINANCIAL_CONTACT}, read = {Role.CONTRACTUAL_CONTACT, Role.FINANCIAL_CONTACT})
     private LocalDate revokationDocumentDate;
 
     @NotNull
+    @AccessFor(init = {Role.CONTRACTUAL_CONTACT, Role.FINANCIAL_CONTACT}, read = {Role.CONTRACTUAL_CONTACT, Role.FINANCIAL_CONTACT})
     private LocalDate validFromDate;
 
+    @AccessFor(init = {Role.CONTRACTUAL_CONTACT, Role.FINANCIAL_CONTACT}, update = {Role.CONTRACTUAL_CONTACT, Role.FINANCIAL_CONTACT}, read = {Role.CONTRACTUAL_CONTACT, Role.FINANCIAL_CONTACT})
     private LocalDate validUntilDate;
 
+    @AccessFor(init = Role.ADMIN, update = Role.ADMIN, read = {Role.CONTRACTUAL_CONTACT, Role.FINANCIAL_CONTACT})
     private LocalDate lastUsedDate;
 
     @Size(max = 160)
+    @AccessFor(init = Role.ADMIN, update = Role.SUPPORTER, read = Role.SUPPORTER)
     private String remark;
 
-
+    @ParentId(resolver = CustomerService.class)
+    @AccessFor(init = {Role.CONTRACTUAL_CONTACT, Role.FINANCIAL_CONTACT}, read = {Role.CONTRACTUAL_CONTACT, Role.FINANCIAL_CONTACT})
     private Long customerId;
 
+    @AccessFor(update = Role.IGNORED, read = {Role.CONTRACTUAL_CONTACT, Role.FINANCIAL_CONTACT})
     private String customerPrefix;
 
     public Long getId() {
@@ -174,7 +192,23 @@ public class SepaMandateDTO implements Serializable {
             ", lastUsedDate='" + getLastUsedDate() + "'" +
             ", remark='" + getRemark() + "'" +
             ", customer=" + getCustomerId() +
-            ", customer='" + getCustomerPrefix() + "'" +
+            ", customerPrefix='" + getCustomerPrefix() + "'" +
             "}";
     }
+
+    @JsonComponent
+    public static class JsonSerializer extends JsonSerializerWithAccessFilter<SepaMandateDTO> {
+
+        public JsonSerializer(final ApplicationContext ctx) {
+            super(ctx);
+        }
+    }
+
+    @JsonComponent
+    public static class JsonDeserializer extends JsonDeserializerWithAccessFilter<SepaMandateDTO> {
+
+        public JsonDeserializer(final ApplicationContext ctx) {
+            super(ctx);
+        }
+    }
 }
diff --git a/src/test/java/org/hostsharing/hsadminng/service/dto/SepaMandateDTOIntTest.java b/src/test/java/org/hostsharing/hsadminng/service/dto/SepaMandateDTOIntTest.java
new file mode 100644
index 00000000..28f706e8
--- /dev/null
+++ b/src/test/java/org/hostsharing/hsadminng/service/dto/SepaMandateDTOIntTest.java
@@ -0,0 +1,189 @@
+package org.hostsharing.hsadminng.service.dto;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.commons.lang3.RandomUtils;
+import org.hostsharing.hsadminng.domain.Customer;
+import org.hostsharing.hsadminng.domain.SepaMandate;
+import org.hostsharing.hsadminng.repository.CustomerRepository;
+import org.hostsharing.hsadminng.repository.MembershipRepository;
+import org.hostsharing.hsadminng.repository.SepaMandateRepository;
+import org.hostsharing.hsadminng.service.MembershipValidator;
+import org.hostsharing.hsadminng.service.SepaMandateService;
+import org.hostsharing.hsadminng.service.accessfilter.JSonBuilder;
+import org.hostsharing.hsadminng.service.accessfilter.Role;
+import org.hostsharing.hsadminng.service.mapper.CustomerMapperImpl;
+import org.hostsharing.hsadminng.service.mapper.MembershipMapperImpl;
+import org.hostsharing.hsadminng.service.mapper.SepaMandateMapper;
+import org.hostsharing.hsadminng.service.mapper.SepaMandateMapperImpl;
+import org.hostsharing.hsadminng.web.rest.errors.BadRequestAlertException;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.junit.MockitoJUnit;
+import org.mockito.junit.MockitoRule;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.autoconfigure.json.JsonTest;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.boot.test.mock.mockito.MockBean;
+import org.springframework.test.context.junit4.SpringRunner;
+
+import javax.persistence.EntityManager;
+import java.io.IOException;
+import java.util.Objects;
+import java.util.Optional;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.catchThrowable;
+import static org.hostsharing.hsadminng.service.accessfilter.MockSecurityContext.givenAuthenticatedUser;
+import static org.hostsharing.hsadminng.service.accessfilter.MockSecurityContext.givenUserHavingRole;
+import static org.hostsharing.hsadminng.service.dto.SepaMandateDTOUnitTest.createSampleDTO;
+import static org.junit.Assert.assertEquals;
+import static org.mockito.BDDMockito.given;
+
+@JsonTest
+@SpringBootTest(classes = {
+    CustomerMapperImpl.class,
+    MembershipMapperImpl.class,
+    SepaMandateMapperImpl.class,
+    SepaMandateDTO.JsonSerializer.class,
+    SepaMandateDTO.JsonDeserializer.class
+})
+@RunWith(SpringRunner.class)
+public class SepaMandateDTOIntTest {
+
+    private static final Long SOME_CUSTOMER_ID = RandomUtils.nextLong(100, 199);
+    private static final Integer SOME_CUSTOMER_REFERENCE = 10001;
+    private static final String SOME_CUSTOMER_PREFIX = "abc";
+    private static final String SOME_CUSTOMER_NAME = "Some Customer Name";
+    private static final Customer SOME_CUSTOMER = new Customer().id(SOME_CUSTOMER_ID)
+        .reference(SOME_CUSTOMER_REFERENCE).prefix(SOME_CUSTOMER_PREFIX).name(SOME_CUSTOMER_NAME);
+
+    private static final Long SOME_SEPA_MANDATE_ID = RandomUtils.nextLong(300, 399);
+    private static final SepaMandate SOME_SEPA_MANDATE = new SepaMandate().id(SOME_SEPA_MANDATE_ID).customer(SOME_CUSTOMER);
+
+    @Rule
+    public MockitoRule mockito = MockitoJUnit.rule();
+
+    @Autowired
+    private ObjectMapper objectMapper;
+
+    @Autowired
+    private SepaMandateMapper sepaMandateMapper;
+
+    @MockBean
+    private SepaMandateRepository sepaMandateRepository;
+
+    @MockBean
+    private CustomerRepository customerRepository;
+
+    @MockBean
+    private MembershipRepository membershipRepository;
+
+    @MockBean
+    private MembershipValidator membershipValidator;
+
+    @MockBean
+    private SepaMandateService sepaMandateService;
+
+    @MockBean
+    private EntityManager em;
+
+    @Before
+    public void init() {
+        given(customerRepository.findById(SOME_CUSTOMER_ID)).willReturn(Optional.of(SOME_CUSTOMER));
+        given(sepaMandateRepository.findById(SOME_SEPA_MANDATE_ID)).willReturn((Optional.of(SOME_SEPA_MANDATE)));
+    }
+
+    @Test
+    public void shouldSerializePartiallyForFinancialCustomerContact() throws JsonProcessingException {
+
+        // given
+        givenAuthenticatedUser();
+        givenUserHavingRole(CustomerDTO.class, SOME_CUSTOMER_ID, Role.FINANCIAL_CONTACT);
+        final SepaMandateDTO given = createSampleDTO(SOME_SEPA_MANDATE_ID, SOME_CUSTOMER_ID);
+
+        // when
+        final String actual = objectMapper.writeValueAsString(given);
+
+        // then
+        given.setRemark(null);
+        assertEquals(createExpectedJSon(given), actual);
+    }
+
+    @Test
+    public void shouldSerializeCompletelyForSupporter() throws JsonProcessingException {
+
+        // given
+        givenAuthenticatedUser();
+        givenUserHavingRole(Role.SUPPORTER);
+        final SepaMandateDTO given = createSampleDTO(SOME_SEPA_MANDATE_ID, SOME_CUSTOMER_ID);
+
+        // when
+        final String actual = objectMapper.writeValueAsString(given);
+
+        // then
+        assertEquals(createExpectedJSon(given), actual);
+    }
+
+    @Test
+    public void shouldNotDeserializeForContractualCustomerContact() {
+        // given
+        givenAuthenticatedUser();
+        givenUserHavingRole(CustomerDTO.class, SOME_CUSTOMER_ID, Role.CONTRACTUAL_CONTACT);
+        final String json = new JSonBuilder()
+            .withFieldValue("id", SOME_SEPA_MANDATE_ID)
+            .withFieldValue("remark", "Updated Remark")
+            .toString();
+
+        // when
+        final Throwable actual = catchThrowable(() -> objectMapper.readValue(json, SepaMandateDTO.class));
+
+        // then
+        assertThat(actual).isInstanceOfSatisfying(BadRequestAlertException.class, bre ->
+            assertThat(bre.getMessage()).isEqualTo("Update of field SepaMandateDTO.remark prohibited for current user role CONTRACTUAL_CONTACT")
+        );
+    }
+
+    @Test
+    public void shouldDeserializeForAdminIfRemarkIsChanged() throws IOException {
+        // given
+        givenAuthenticatedUser();
+        givenUserHavingRole(Role.ADMIN);
+        final String json = new JSonBuilder()
+            .withFieldValue("id", SOME_SEPA_MANDATE_ID)
+            .withFieldValue("remark", "Updated Remark")
+            .toString();
+
+        // when
+        final SepaMandateDTO actual = objectMapper.readValue(json, SepaMandateDTO.class);
+
+        // then
+        final SepaMandateDTO expected = new SepaMandateDTO();
+        expected.setId(SOME_SEPA_MANDATE_ID);
+        expected.setCustomerId(SOME_CUSTOMER_ID);
+        expected.setRemark("Updated Remark");
+        expected.setCustomerPrefix(SOME_CUSTOMER_PREFIX);
+        assertThat(actual).isEqualToIgnoringGivenFields(expected, "displayLabel");
+    }
+
+    // --- only test fixture below ---
+
+    private String createExpectedJSon(SepaMandateDTO dto) {
+        return new JSonBuilder()
+            .withFieldValueIfPresent("id", dto.getId())
+            .withFieldValueIfPresent("reference", dto.getReference())
+            .withFieldValueIfPresent("iban", dto.getIban())
+            .withFieldValueIfPresent("bic", dto.getBic())
+            .withFieldValueIfPresent("grantingDocumentDate", Objects.toString(dto.getGrantingDocumentDate()))
+            .withFieldValueIfPresent("revokationDocumentDate", Objects.toString(dto.getRevokationDocumentDate()))
+            .withFieldValueIfPresent("validFromDate", Objects.toString(dto.getValidFromDate()))
+            .withFieldValueIfPresent("validUntilDate", Objects.toString(dto.getValidUntilDate()))
+            .withFieldValueIfPresent("lastUsedDate", Objects.toString(dto.getLastUsedDate()))
+            .withFieldValueIfPresent("remark", dto.getRemark())
+            .withFieldValueIfPresent("customerId", dto.getCustomerId())
+            .withFieldValue("customerPrefix", dto.getCustomerPrefix())
+            .toString();
+    }
+}
diff --git a/src/test/java/org/hostsharing/hsadminng/service/dto/SepaMandateDTOUnitTest.java b/src/test/java/org/hostsharing/hsadminng/service/dto/SepaMandateDTOUnitTest.java
new file mode 100644
index 00000000..aa3a06da
--- /dev/null
+++ b/src/test/java/org/hostsharing/hsadminng/service/dto/SepaMandateDTOUnitTest.java
@@ -0,0 +1,96 @@
+package org.hostsharing.hsadminng.service.dto;
+
+import org.apache.commons.lang3.RandomStringUtils;
+import org.apache.commons.lang3.RandomUtils;
+import org.hostsharing.hsadminng.service.accessfilter.Role;
+import org.junit.Test;
+
+import java.time.LocalDate;
+
+public class SepaMandateDTOUnitTest extends AccessMappingsUnitTestBase<SepaMandateDTO> {
+
+    public SepaMandateDTOUnitTest() {
+        super(SepaMandateDTO.class, SepaMandateDTOUnitTest::createSampleDTO, SepaMandateDTOUnitTest::createRandomDTO);
+    }
+
+    @Test
+    public void shouldHaveProperAccessForAdmin() {
+        initAccessFor(SepaMandateDTO.class, Role.ADMIN).shouldBeExactlyFor(
+            "grantingDocumentDate", "bic", "remark", "validUntilDate", "customerId", "validFromDate",
+            "iban", "revokationDocumentDate", "lastUsedDate", "reference");
+        updateAccessFor(SepaMandateDTO.class, Role.ADMIN).shouldBeExactlyFor(
+            "remark", "validUntilDate", "revokationDocumentDate", "lastUsedDate");
+        readAccessFor(SepaMandateDTO.class, Role.ADMIN).shouldBeForAllFields();
+    }
+
+    @Test
+    public void shouldHaveProperAccessForSupporter() {
+        initAccessFor(SepaMandateDTO.class, Role.SUPPORTER).shouldBeExactlyFor(
+            "grantingDocumentDate", "bic", "validUntilDate", "customerId", "validFromDate", "iban", "reference");
+        updateAccessFor(SepaMandateDTO.class, Role.SUPPORTER).shouldBeExactlyFor(
+            "remark", "validUntilDate", "revokationDocumentDate");
+        readAccessFor(SepaMandateDTO.class, Role.SUPPORTER).shouldBeForAllFields();
+    }
+
+    @Test
+    public void shouldHaveProperAccessForContractualContact() {
+        initAccessFor(SepaMandateDTO.class, Role.CONTRACTUAL_CONTACT).shouldBeExactlyFor(
+            "grantingDocumentDate", "bic", "validUntilDate", "customerId", "validFromDate", "iban", "reference");
+        updateAccessFor(SepaMandateDTO.class, Role.CONTRACTUAL_CONTACT).shouldBeExactlyFor(
+            "validUntilDate", "revokationDocumentDate");
+        readAccessFor(SepaMandateDTO.class, Role.CONTRACTUAL_CONTACT).shouldBeExactlyFor(
+            "grantingDocumentDate", "bic", "id", "validUntilDate", "customerId", "validFromDate", "iban",
+            "revokationDocumentDate", "customerPrefix", "lastUsedDate", "reference");
+    }
+
+    @Test
+    public void shouldHaveNoAccessForTechnicalContact() {
+        initAccessFor(SepaMandateDTO.class, Role.TECHNICAL_CONTACT).shouldBeForNothing();
+        updateAccessFor(SepaMandateDTO.class, Role.TECHNICAL_CONTACT).shouldBeForNothing();
+        readAccessFor(SepaMandateDTO.class, Role.TECHNICAL_CONTACT).shouldBeForNothing();
+    }
+
+    @Test
+    public void shouldHaveNoAccessForNormalUsersWithinCustomerRealm() {
+        initAccessFor(SepaMandateDTO.class, Role.ANY_CUSTOMER_USER).shouldBeForNothing();
+        updateAccessFor(SepaMandateDTO.class, Role.ANY_CUSTOMER_USER).shouldBeForNothing();
+        readAccessFor(SepaMandateDTO.class, Role.ANY_CUSTOMER_USER).shouldBeForNothing();
+    }
+
+    // --- only test fixture below ---
+
+    public static SepaMandateDTO createSampleDTO(final Long id, final Long parentId) {
+        final SepaMandateDTO dto = new SepaMandateDTO();
+        dto.setId(id);
+        dto.setReference("Some Reference");
+        dto.setGrantingDocumentDate(LocalDate.parse("2000-12-07"));
+        dto.setRevokationDocumentDate(LocalDate.parse("2019-04-27"));
+        dto.setValidFromDate(LocalDate.parse("2000-12-18"));
+        dto.setValidUntilDate(LocalDate.parse("2019-05-31"));
+        dto.setLastUsedDate(LocalDate.parse("2019-04-04"));
+        dto.setIban("DE1234IBAN");
+        dto.setBic("BIC1234");
+        dto.setRemark("Some Remark");
+        dto.setCustomerId(parentId);
+        dto.setCustomerPrefix("abc");
+        return dto;
+    }
+
+    public static SepaMandateDTO createRandomDTO(final Long id, final Long parentId) {
+        final SepaMandateDTO dto = new SepaMandateDTO();
+        dto.setId(id);
+        dto.setReference(RandomStringUtils.randomAlphanumeric(10));
+        final LocalDate randomDate = LocalDate.parse("2000-12-07").plusDays(RandomUtils.nextInt(1, 999));
+        dto.setGrantingDocumentDate(randomDate);
+        dto.setRevokationDocumentDate(randomDate.plusDays(RandomUtils.nextInt(1100, 2999)));
+        dto.setValidFromDate(randomDate.plusDays(RandomUtils.nextInt(0, 7)));
+        dto.setValidUntilDate(dto.getRevokationDocumentDate().plusDays(7));
+        dto.setLastUsedDate(dto.getRevokationDocumentDate().minusDays(20));
+        dto.setIban(RandomStringUtils.randomAlphanumeric(20).toUpperCase());
+        dto.setBic(RandomStringUtils.randomAlphanumeric(10).toUpperCase());
+        dto.setRemark(RandomStringUtils.randomAlphanumeric(20).toUpperCase());
+        dto.setCustomerId(parentId);
+        dto.setCustomerPrefix(RandomStringUtils.randomAlphabetic(3).toLowerCase());
+        return dto;
+    }
+}
diff --git a/src/test/java/org/hostsharing/hsadminng/web/rest/SepaMandateResourceIntTest.java b/src/test/java/org/hostsharing/hsadminng/web/rest/SepaMandateResourceIntTest.java
index ecd90cc7..0414ce68 100644
--- a/src/test/java/org/hostsharing/hsadminng/web/rest/SepaMandateResourceIntTest.java
+++ b/src/test/java/org/hostsharing/hsadminng/web/rest/SepaMandateResourceIntTest.java
@@ -6,6 +6,8 @@ import org.hostsharing.hsadminng.domain.SepaMandate;
 import org.hostsharing.hsadminng.repository.SepaMandateRepository;
 import org.hostsharing.hsadminng.service.SepaMandateQueryService;
 import org.hostsharing.hsadminng.service.SepaMandateService;
+import org.hostsharing.hsadminng.service.accessfilter.MockSecurityContext;
+import org.hostsharing.hsadminng.service.accessfilter.Role;
 import org.hostsharing.hsadminng.service.dto.SepaMandateDTO;
 import org.hostsharing.hsadminng.service.mapper.SepaMandateMapper;
 import org.hostsharing.hsadminng.web.rest.errors.ExceptionTranslator;
@@ -104,6 +106,9 @@ public class SepaMandateResourceIntTest {
 
     @Before
     public void setup() {
+        MockSecurityContext.givenAuthenticatedUser();
+        MockSecurityContext.givenUserHavingRole(Role.ADMIN);
+
         MockitoAnnotations.initMocks(this);
         final SepaMandateResource sepaMandateResource = new SepaMandateResource(sepaMandateService, sepaMandateQueryService);
         this.restSepaMandateMockMvc = MockMvcBuilders.standaloneSetup(sepaMandateResource)
@@ -173,6 +178,7 @@ public class SepaMandateResourceIntTest {
 
         // Create the SepaMandate
         SepaMandateDTO sepaMandateDTO = sepaMandateMapper.toDto(sepaMandate);
+        sepaMandateDTO.setCustomerPrefix(null);
         restSepaMandateMockMvc.perform(post("/api/sepa-mandates")
             .contentType(TestUtil.APPLICATION_JSON_UTF8)
             .content(TestUtil.convertObjectToJsonBytes(sepaMandateDTO)))
@@ -281,15 +287,15 @@ public class SepaMandateResourceIntTest {
             .andExpect(status().isOk())
             .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
             .andExpect(jsonPath("$.[*].id").value(hasItem(sepaMandate.getId().intValue())))
-            .andExpect(jsonPath("$.[*].reference").value(hasItem(DEFAULT_REFERENCE.toString())))
-            .andExpect(jsonPath("$.[*].iban").value(hasItem(DEFAULT_IBAN.toString())))
-            .andExpect(jsonPath("$.[*].bic").value(hasItem(DEFAULT_BIC.toString())))
+            .andExpect(jsonPath("$.[*].reference").value(hasItem(DEFAULT_REFERENCE)))
+            .andExpect(jsonPath("$.[*].iban").value(hasItem(DEFAULT_IBAN)))
+            .andExpect(jsonPath("$.[*].bic").value(hasItem(DEFAULT_BIC)))
             .andExpect(jsonPath("$.[*].grantingDocumentDate").value(hasItem(DEFAULT_GRANTING_DOCUMENT_DATE.toString())))
             .andExpect(jsonPath("$.[*].revokationDocumentDate").value(hasItem(DEFAULT_REVOKATION_DOCUMENT_DATE.toString())))
             .andExpect(jsonPath("$.[*].validFromDate").value(hasItem(DEFAULT_VALID_FROM_DATE.toString())))
             .andExpect(jsonPath("$.[*].validUntilDate").value(hasItem(DEFAULT_VALID_UNTIL_DATE.toString())))
             .andExpect(jsonPath("$.[*].lastUsedDate").value(hasItem(DEFAULT_LAST_USED_DATE.toString())))
-            .andExpect(jsonPath("$.[*].remark").value(hasItem(DEFAULT_REMARK.toString())));
+            .andExpect(jsonPath("$.[*].remark").value(hasItem(DEFAULT_REMARK)));
     }
     
     @Test
@@ -303,15 +309,15 @@ public class SepaMandateResourceIntTest {
             .andExpect(status().isOk())
             .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
             .andExpect(jsonPath("$.id").value(sepaMandate.getId().intValue()))
-            .andExpect(jsonPath("$.reference").value(DEFAULT_REFERENCE.toString()))
-            .andExpect(jsonPath("$.iban").value(DEFAULT_IBAN.toString()))
-            .andExpect(jsonPath("$.bic").value(DEFAULT_BIC.toString()))
+            .andExpect(jsonPath("$.reference").value(DEFAULT_REFERENCE))
+            .andExpect(jsonPath("$.iban").value(DEFAULT_IBAN))
+            .andExpect(jsonPath("$.bic").value(DEFAULT_BIC))
             .andExpect(jsonPath("$.grantingDocumentDate").value(DEFAULT_GRANTING_DOCUMENT_DATE.toString()))
             .andExpect(jsonPath("$.revokationDocumentDate").value(DEFAULT_REVOKATION_DOCUMENT_DATE.toString()))
             .andExpect(jsonPath("$.validFromDate").value(DEFAULT_VALID_FROM_DATE.toString()))
             .andExpect(jsonPath("$.validUntilDate").value(DEFAULT_VALID_UNTIL_DATE.toString()))
             .andExpect(jsonPath("$.lastUsedDate").value(DEFAULT_LAST_USED_DATE.toString()))
-            .andExpect(jsonPath("$.remark").value(DEFAULT_REMARK.toString()));
+            .andExpect(jsonPath("$.remark").value(DEFAULT_REMARK));
     }
 
     @Test
@@ -880,12 +886,7 @@ public class SepaMandateResourceIntTest {
         // Disconnect from session so that the updates on updatedSepaMandate are not directly saved in db
         em.detach(updatedSepaMandate);
         updatedSepaMandate
-            .reference(UPDATED_REFERENCE)
-            .iban(UPDATED_IBAN)
-            .bic(UPDATED_BIC)
-            .grantingDocumentDate(UPDATED_GRANTING_DOCUMENT_DATE)
             .revokationDocumentDate(UPDATED_REVOKATION_DOCUMENT_DATE)
-            .validFromDate(UPDATED_VALID_FROM_DATE)
             .validUntilDate(UPDATED_VALID_UNTIL_DATE)
             .lastUsedDate(UPDATED_LAST_USED_DATE)
             .remark(UPDATED_REMARK);
@@ -900,12 +901,12 @@ public class SepaMandateResourceIntTest {
         List<SepaMandate> sepaMandateList = sepaMandateRepository.findAll();
         assertThat(sepaMandateList).hasSize(databaseSizeBeforeUpdate);
         SepaMandate testSepaMandate = sepaMandateList.get(sepaMandateList.size() - 1);
-        assertThat(testSepaMandate.getReference()).isEqualTo(UPDATED_REFERENCE);
-        assertThat(testSepaMandate.getIban()).isEqualTo(UPDATED_IBAN);
-        assertThat(testSepaMandate.getBic()).isEqualTo(UPDATED_BIC);
-        assertThat(testSepaMandate.getGrantingDocumentDate()).isEqualTo(UPDATED_GRANTING_DOCUMENT_DATE);
+        assertThat(testSepaMandate.getReference()).isEqualTo(DEFAULT_REFERENCE);
+        assertThat(testSepaMandate.getIban()).isEqualTo(DEFAULT_IBAN);
+        assertThat(testSepaMandate.getBic()).isEqualTo(DEFAULT_BIC);
+        assertThat(testSepaMandate.getGrantingDocumentDate()).isEqualTo(DEFAULT_GRANTING_DOCUMENT_DATE);
         assertThat(testSepaMandate.getRevokationDocumentDate()).isEqualTo(UPDATED_REVOKATION_DOCUMENT_DATE);
-        assertThat(testSepaMandate.getValidFromDate()).isEqualTo(UPDATED_VALID_FROM_DATE);
+        assertThat(testSepaMandate.getValidFromDate()).isEqualTo(DEFAULT_VALID_FROM_DATE);
         assertThat(testSepaMandate.getValidUntilDate()).isEqualTo(UPDATED_VALID_UNTIL_DATE);
         assertThat(testSepaMandate.getLastUsedDate()).isEqualTo(UPDATED_LAST_USED_DATE);
         assertThat(testSepaMandate.getRemark()).isEqualTo(UPDATED_REMARK);
diff --git a/src/test/java/org/hostsharing/hsadminng/web/rest/SepaMandateResourceUnitTest.java b/src/test/java/org/hostsharing/hsadminng/web/rest/SepaMandateResourceUnitTest.java
new file mode 100644
index 00000000..6bf0d00e
--- /dev/null
+++ b/src/test/java/org/hostsharing/hsadminng/web/rest/SepaMandateResourceUnitTest.java
@@ -0,0 +1,56 @@
+package org.hostsharing.hsadminng.web.rest;
+
+import org.hostsharing.hsadminng.service.dto.SepaMandateDTO;
+import org.hostsharing.hsadminng.service.dto.SepaMandateDTOUnitTest;
+import org.hostsharing.hsadminng.web.rest.errors.BadRequestAlertException;
+import org.junit.Rule;
+import org.junit.Test;
+import org.mockito.InjectMocks;
+import org.mockito.junit.MockitoJUnit;
+import org.mockito.junit.MockitoRule;
+
+import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
+import static org.assertj.core.api.ThrowableAssert.catchThrowable;
+
+// Currently this class tests mostly special 'bad paths'
+// which make little sense to test in *ResourceIntTest.
+public class SepaMandateResourceUnitTest {
+
+    @Rule
+    public MockitoRule mockitoRule = MockitoJUnit.rule();
+
+    @InjectMocks
+    private SepaMandateResource sepaMandateResource;
+
+    @Test
+    public void createSepaMandateWithoutIdThrowsBadRequestException() {
+
+        // given
+        final SepaMandateDTO givenDto = SepaMandateDTOUnitTest.createRandomDTO(null, 1L);
+
+        // when
+        final Throwable actual = catchThrowable(() -> sepaMandateResource.updateSepaMandate(givenDto));
+
+        // then
+        assertThat(actual).isInstanceOfSatisfying(BadRequestAlertException.class, bre -> {
+            assertThat(bre.getErrorKey()).isEqualTo("idnull");
+            assertThat(bre.getParam()).isEqualTo("sepaMandate");
+        });
+    }
+
+    @Test
+    public void createSepaMandateWithIdThrowsBadRequestException() {
+
+        // given
+        final SepaMandateDTO givenDto = SepaMandateDTOUnitTest.createRandomDTO(2L, 1L);
+
+        // when
+        final Throwable actual = catchThrowable(() -> sepaMandateResource.createSepaMandate(givenDto));
+
+        // then
+        assertThat(actual).isInstanceOfSatisfying(BadRequestAlertException.class, bre -> {
+            assertThat(bre.getErrorKey()).isEqualTo("idexists");
+            assertThat(bre.getParam()).isEqualTo("sepaMandate");
+        });
+    }
+}