Initial drop of tests 00/118100/1
authorClaudio D. Gasparini <claudio.gasparini@pantheon.tech>
Fri, 19 Feb 2021 11:26:22 +0000 (12:26 +0100)
committerClaudio D. Gasparini <claudio.gasparini@pantheon.tech>
Fri, 19 Feb 2021 11:34:44 +0000 (12:34 +0100)
Issue-ID: CPS-243
Signed-off-by: Claudio D. Gasparini <claudio.gasparini@pantheon.tech>
Change-Id: I9562bcb172a8341885a4a0165d20baba71f9d7fb

pom.xml
src/test/java/org/onap/cps/tdmt/client/CpsRestClientTest.java [new file with mode: 0644]
src/test/java/org/onap/cps/tdmt/model/ModelTest.java [new file with mode: 0644]
src/test/java/org/onap/cps/tdmt/rest/ExecutionControllerTest.java [new file with mode: 0644]
src/test/java/org/onap/cps/tdmt/rest/TemplateControllerTest.java [new file with mode: 0644]
src/test/java/org/onap/cps/tdmt/service/ExecutionBusinessLogicTest.java [new file with mode: 0644]
src/test/java/org/onap/cps/tdmt/service/TemplateBusinessLogicTest.java [new file with mode: 0644]
src/test/resources/application-test.properties [new file with mode: 0644]

diff --git a/pom.xml b/pom.xml
index 058e9ae..13ac02c 100644 (file)
--- a/pom.xml
+++ b/pom.xml
             <groupId>org.apache.tomcat.embed</groupId>
             <artifactId>tomcat-embed-core</artifactId>
         </dependency>
+        <!--Test dependencies-->
+        <dependency>
+            <groupId>com.openpojo</groupId>
+            <artifactId>openpojo</artifactId>
+            <version>0.8.13</version>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>junit</groupId>
+            <artifactId>junit</artifactId>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-test</artifactId>
+            <scope>test</scope>
+        </dependency>
     </dependencies>
 
     <build>
diff --git a/src/test/java/org/onap/cps/tdmt/client/CpsRestClientTest.java b/src/test/java/org/onap/cps/tdmt/client/CpsRestClientTest.java
new file mode 100644 (file)
index 0000000..ca03fdd
--- /dev/null
@@ -0,0 +1,108 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP
+ * ================================================================================
+ * Copyright (C) 2021 Wipro Limited.
+ * ================================================================================
+ * 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
+ *
+ *      http://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.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.cps.tdmt.client;
+
+import static org.junit.Assert.assertEquals;
+
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.ExpectedException;
+import org.junit.runner.RunWith;
+import org.mockito.ArgumentMatchers;
+import org.mockito.Mockito;
+import org.onap.cps.tdmt.exception.CpsException;
+import org.onap.cps.tdmt.model.AppConfiguration;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.context.properties.EnableConfigurationProperties;
+import org.springframework.boot.test.context.TestConfiguration;
+import org.springframework.boot.test.mock.mockito.MockBean;
+import org.springframework.context.annotation.Bean;
+import org.springframework.http.HttpHeaders;
+import org.springframework.http.HttpMethod;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.MediaType;
+import org.springframework.http.ResponseEntity;
+import org.springframework.test.context.TestPropertySource;
+import org.springframework.test.context.junit4.SpringRunner;
+import org.springframework.web.client.RestClientException;
+import org.springframework.web.client.RestTemplate;
+
+@RunWith(SpringRunner.class)
+@EnableConfigurationProperties(AppConfiguration.class)
+@TestPropertySource("classpath:application-test.properties")
+public class CpsRestClientTest {
+
+    @TestConfiguration
+    static class CpsRestClientTestContextConfiguration {
+
+        @Bean
+        public CpsRestClient cpsRestClient() {
+            return new CpsRestClient();
+        }
+    }
+
+    @Autowired
+    private CpsRestClient cpsRestClient;
+
+    @MockBean
+    private RestTemplate restTemplate;
+
+    @Rule
+    public ExpectedException exception = ExpectedException.none();
+
+    @Test
+    public void testFetchNode() throws Exception {
+        final HttpHeaders responseHeaders = new HttpHeaders();
+        responseHeaders.setContentType(MediaType.APPLICATION_JSON);
+        final ResponseEntity<String> response = new ResponseEntity<>("sample response", responseHeaders,
+            HttpStatus.OK);
+        Mockito.when(restTemplate.exchange(ArgumentMatchers.anyString(),
+            ArgumentMatchers.any(HttpMethod.class),
+            ArgumentMatchers.any(),
+            ArgumentMatchers.<Class<String>>any()))
+            .thenReturn(response);
+        assertEquals("sample response", cpsRestClient.fetchNode("coverage-area-onap", "sample"));
+
+        final ResponseEntity<String> errorResponse = new ResponseEntity<>("sample response",
+            responseHeaders, HttpStatus.NOT_FOUND);
+        Mockito.when(restTemplate.exchange(ArgumentMatchers.anyString(),
+            ArgumentMatchers.any(HttpMethod.class),
+            ArgumentMatchers.any(),
+            ArgumentMatchers.<Class<String>>any()))
+            .thenReturn(errorResponse);
+        exception.expect(CpsException.class);
+        exception.expectMessage("Response code from CPS other than 200: 404");
+        cpsRestClient.fetchNode("coverage-area-onap", "sample");
+
+    }
+
+    @Test
+    public void testFetchNodeException() throws Exception {
+        Mockito.when(restTemplate.exchange(ArgumentMatchers.anyString(),
+            ArgumentMatchers.any(HttpMethod.class),
+            ArgumentMatchers.any(),
+            ArgumentMatchers.<Class<String>>any()))
+            .thenThrow(new RestClientException("Connection refused"));
+        exception.expect(CpsException.class);
+        exception.expectMessage("Connection refused");
+        cpsRestClient.fetchNode("coverage-area-onap", "sample");
+    }
+}
diff --git a/src/test/java/org/onap/cps/tdmt/model/ModelTest.java b/src/test/java/org/onap/cps/tdmt/model/ModelTest.java
new file mode 100644 (file)
index 0000000..0ac8475
--- /dev/null
@@ -0,0 +1,49 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP
+ * ================================================================================
+ * Copyright (C) 2021 Wipro Limited.
+ * ================================================================================
+ * 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
+ *
+ *      http://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.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.cps.tdmt.model;
+
+import com.openpojo.reflection.filters.FilterPackageInfo;
+import com.openpojo.validation.Validator;
+import com.openpojo.validation.ValidatorBuilder;
+import com.openpojo.validation.rule.impl.GetterMustExistRule;
+import com.openpojo.validation.rule.impl.SetterMustExistRule;
+import com.openpojo.validation.test.impl.GetterTester;
+import com.openpojo.validation.test.impl.SetterTester;
+import org.junit.Test;
+
+public class ModelTest {
+
+    private static final String POJO_PACKAGE = "org.onap.cps.tdmt.model";
+
+    @Test
+    public void testModels() {
+        final Validator validator = ValidatorBuilder.create()
+            .with(new GetterMustExistRule())
+            .with(new SetterMustExistRule())
+            .with(new SetterTester())
+            .with(new GetterTester())
+            .build();
+
+        validator.validate(POJO_PACKAGE, new FilterPackageInfo());
+
+    }
+
+}
diff --git a/src/test/java/org/onap/cps/tdmt/rest/ExecutionControllerTest.java b/src/test/java/org/onap/cps/tdmt/rest/ExecutionControllerTest.java
new file mode 100644 (file)
index 0000000..38f412f
--- /dev/null
@@ -0,0 +1,119 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP
+ * ================================================================================
+ * Copyright (C) 2021 Wipro Limited.
+ * ================================================================================
+ * 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
+ *
+ *      http://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.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.cps.tdmt.rest;
+
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import java.util.HashMap;
+import java.util.Map;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.ArgumentMatchers;
+import org.mockito.Mockito;
+import org.onap.cps.tdmt.exception.ExecuteException;
+import org.onap.cps.tdmt.exception.RecordNotFoundException;
+import org.onap.cps.tdmt.model.ExecutionRequest;
+import org.onap.cps.tdmt.service.ExecutionBusinessLogic;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
+import org.springframework.boot.test.mock.mockito.MockBean;
+import org.springframework.http.MediaType;
+import org.springframework.test.context.junit4.SpringRunner;
+import org.springframework.test.web.servlet.MockMvc;
+
+@RunWith(SpringRunner.class)
+@WebMvcTest(ExecutionController.class)
+public class ExecutionControllerTest {
+
+    @Autowired
+    private MockMvc mockMvc;
+
+    @MockBean
+    private ExecutionBusinessLogic executionBusinessLogic;
+
+    private ObjectMapper mapper;
+    private String requestJson;
+    private String executePath;
+
+    /**
+     * Setup variables before test.
+     *
+     */
+    @Before
+    public void setup() throws Exception {
+        executePath = "/execute/ran-network/getNbr";
+        final Map<String, String> input = new HashMap<>();
+        input.put("coverageArea", "Zone 1");
+        final ExecutionRequest request = new ExecutionRequest(input);
+        mapper = new ObjectMapper();
+        requestJson = mapper.writeValueAsString(request);
+    }
+
+    @Test
+    public void testExecuteTemplate() throws Exception {
+        final String result = "{\"key\": \"value\"}";
+        Mockito.when(executionBusinessLogic
+            .executeTemplate(ArgumentMatchers.any(), ArgumentMatchers.any(),
+                ArgumentMatchers.any()))
+            .thenReturn(result);
+        mockMvc.perform(post(executePath).contentType(MediaType.APPLICATION_JSON)
+            .characterEncoding("utf-8")
+            .content(requestJson).accept(MediaType.APPLICATION_JSON))
+            .andExpect(status().isOk())
+            .andExpect(content().string(result));
+
+        Mockito.when(executionBusinessLogic
+            .executeTemplate(ArgumentMatchers.any(), ArgumentMatchers.any(),
+                ArgumentMatchers.any()))
+            .thenThrow(new RecordNotFoundException("Template does not exist"));
+        mockMvc.perform(post(executePath).contentType(MediaType.APPLICATION_JSON)
+            .characterEncoding("utf-8")
+            .content(requestJson).accept(MediaType.APPLICATION_JSON))
+            .andExpect(status().isNotFound());
+
+        mockMvc.perform(post(executePath).contentType(MediaType.APPLICATION_JSON)
+            .characterEncoding("utf-8")
+            .content("{\"bad\": \"request\"").accept(MediaType.APPLICATION_JSON))
+            .andExpect(status().isBadRequest());
+    }
+
+    @Test
+    public void testExecuteTemplateException() throws Exception {
+        final String responseJson = "{\n"
+            + "  \"message\": \"Error while executing template\",\n"
+            + "  \"details\": [\"Response from CPS other than 200: 404\"]\n"
+            + "}";
+
+        Mockito.when(executionBusinessLogic
+            .executeTemplate(ArgumentMatchers.any(), ArgumentMatchers.any(),
+                ArgumentMatchers.any()))
+            .thenThrow(new ExecuteException("Response from CPS other than 200: 404"));
+        mockMvc.perform(post(executePath).contentType(MediaType.APPLICATION_JSON)
+            .characterEncoding("utf-8")
+            .content(requestJson).accept(MediaType.APPLICATION_JSON))
+            .andExpect(status().isOk())
+            .andExpect(content().json(responseJson));
+    }
+}
diff --git a/src/test/java/org/onap/cps/tdmt/rest/TemplateControllerTest.java b/src/test/java/org/onap/cps/tdmt/rest/TemplateControllerTest.java
new file mode 100644 (file)
index 0000000..7e31265
--- /dev/null
@@ -0,0 +1,134 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP
+ * ================================================================================
+ * Copyright (C) 2021 Wipro Limited.
+ * ================================================================================
+ * 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
+ *
+ *      http://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.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.cps.tdmt.rest;
+
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import java.util.ArrayList;
+import java.util.List;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.ArgumentMatchers;
+import org.mockito.Mockito;
+import org.onap.cps.tdmt.exception.RecordNotFoundException;
+import org.onap.cps.tdmt.model.Template;
+import org.onap.cps.tdmt.model.TemplateRequest;
+import org.onap.cps.tdmt.service.TemplateBusinessLogic;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
+import org.springframework.boot.test.mock.mockito.MockBean;
+import org.springframework.http.MediaType;
+import org.springframework.test.context.junit4.SpringRunner;
+import org.springframework.test.web.servlet.MockMvc;
+
+@RunWith(SpringRunner.class)
+@WebMvcTest(TemplateController.class)
+public class TemplateControllerTest {
+
+    @Autowired
+    private MockMvc mockMvc;
+
+    @MockBean
+    private TemplateBusinessLogic templateBusinessLogic;
+
+    private ObjectMapper mapper;
+
+    private Template template;
+
+    @Before
+    public void setup() {
+        mapper = new ObjectMapper();
+        template = new Template("getNbr", "ran-network", "sample");
+    }
+
+    @Test
+    public void testCreateTemplate() throws Exception {
+        final TemplateRequest emptyTemplateRequest = new TemplateRequest();
+        emptyTemplateRequest.setId("getNbr");
+        emptyTemplateRequest.setSchemaSet("ran-network");
+        final String emptyTemplateJson = mapper.writeValueAsString(emptyTemplateRequest);
+        mockMvc.perform(
+            post("/templates").contentType(MediaType.APPLICATION_JSON).characterEncoding("utf-8")
+                .content(emptyTemplateJson).accept(MediaType.APPLICATION_JSON))
+            .andExpect(status().isBadRequest());
+
+        final TemplateRequest request = new TemplateRequest("getNbr", "ran-network", "sample");
+        final String templateJson = mapper.writeValueAsString(request);
+        Mockito.when(templateBusinessLogic.createTemplate(ArgumentMatchers.any()))
+            .thenReturn(template);
+        mockMvc.perform(
+            post("/templates").contentType(MediaType.APPLICATION_JSON).characterEncoding("utf-8")
+                .content(templateJson).accept(MediaType.APPLICATION_JSON))
+            .andExpect(status().isCreated())
+            .andExpect(content().json(templateJson));
+    }
+
+    @Test
+    public void testGetAllTemplates() throws Exception {
+        final List<Template> templates = new ArrayList<>();
+        templates.add(template);
+        final String templatesJson = mapper.writeValueAsString(templates);
+        Mockito.when(templateBusinessLogic.getAllTemplates()).thenReturn(templates);
+        mockMvc.perform(get("/templates").accept(MediaType.APPLICATION_JSON))
+            .andExpect(status().isOk())
+            .andExpect(content().json(templatesJson));
+
+        Mockito.when(templateBusinessLogic.getAllTemplates()).thenReturn(new ArrayList<>());
+        mockMvc.perform(get("/templates").accept(MediaType.APPLICATION_JSON))
+            .andExpect(status().isNotFound());
+
+    }
+
+    @Test
+    public void testGetTemplate() throws Exception {
+        final String templateJson = mapper.writeValueAsString(template);
+        Mockito.when(templateBusinessLogic.getTemplate(ArgumentMatchers.any()))
+            .thenReturn(template);
+        mockMvc.perform(get("/templates/ran-network/getNbr").accept(MediaType.APPLICATION_JSON))
+            .andExpect(status().isOk())
+            .andExpect(content().json(templateJson));
+
+        Mockito.when(templateBusinessLogic.getTemplate(ArgumentMatchers.any()))
+            .thenThrow(new RecordNotFoundException("Template not found"));
+        mockMvc.perform(get("/templates/ran-network/getNbr").accept(MediaType.APPLICATION_JSON))
+            .andExpect(status().isNotFound());
+    }
+
+    @Test
+    public void testDeleteTemplate() throws Exception {
+        Mockito.doNothing().when(templateBusinessLogic).deleteTemplate(ArgumentMatchers.any());
+        mockMvc.perform(delete("/templates/ran-network/getNbr").accept(MediaType.APPLICATION_JSON))
+            .andExpect(status().isOk());
+
+        Mockito.doThrow(new RecordNotFoundException("Template not found"))
+            .when(templateBusinessLogic)
+            .deleteTemplate(ArgumentMatchers.any());
+        mockMvc.perform(delete("/templates/ran-network/getNbr").accept(MediaType.APPLICATION_JSON))
+            .andExpect(status().isNotFound());
+    }
+
+}
diff --git a/src/test/java/org/onap/cps/tdmt/service/ExecutionBusinessLogicTest.java b/src/test/java/org/onap/cps/tdmt/service/ExecutionBusinessLogicTest.java
new file mode 100644 (file)
index 0000000..70c6f3c
--- /dev/null
@@ -0,0 +1,147 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP
+ * ================================================================================
+ * Copyright (C) 2021 Wipro Limited.
+ * ================================================================================
+ * 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
+ *
+ *      http://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.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.cps.tdmt.service;
+
+import static org.junit.Assert.assertEquals;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Optional;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.ExpectedException;
+import org.junit.runner.RunWith;
+import org.mockito.ArgumentMatchers;
+import org.mockito.Mockito;
+import org.onap.cps.tdmt.client.CpsRestClient;
+import org.onap.cps.tdmt.db.TemplateRepository;
+import org.onap.cps.tdmt.exception.CpsException;
+import org.onap.cps.tdmt.exception.ExecuteException;
+import org.onap.cps.tdmt.exception.RecordNotFoundException;
+import org.onap.cps.tdmt.model.AppConfiguration;
+import org.onap.cps.tdmt.model.ExecutionRequest;
+import org.onap.cps.tdmt.model.Template;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.context.properties.EnableConfigurationProperties;
+import org.springframework.boot.test.context.TestConfiguration;
+import org.springframework.boot.test.mock.mockito.MockBean;
+import org.springframework.context.annotation.Bean;
+import org.springframework.test.context.TestPropertySource;
+import org.springframework.test.context.junit4.SpringRunner;
+
+@RunWith(SpringRunner.class)
+@EnableConfigurationProperties(AppConfiguration.class)
+@TestPropertySource("classpath:application-test.properties")
+public class ExecutionBusinessLogicTest {
+
+    @TestConfiguration
+    static class ExecutionBusinessLogicTestContextConfiguration {
+
+        @Bean
+        public ExecutionBusinessLogic executionBusinessLogic() {
+            return new ExecutionBusinessLogic();
+        }
+    }
+
+    @Autowired
+    private ExecutionBusinessLogic executionBusinessLogic;
+
+    @MockBean
+    private TemplateRepository templateRepository;
+
+    @MockBean
+    private CpsRestClient cpsRestClient;
+
+    @Rule
+    public ExpectedException exception = ExpectedException.none();
+
+    private ExecutionRequest request;
+
+    private Template template;
+
+    /**
+     * Setup variables before test.
+     *
+     */
+    @Before
+    public void setup() {
+        final Map<String, String> input = new HashMap<>();
+        input.put("coverageArea", "Zone 1");
+        request = new ExecutionRequest(input);
+        final String xpathTemplate = "/ran-coverage-area/pLMNIdList[@mcc='310' and @mnc='410']"
+            + "/coverage-area[@coverageArea='{{coverageArea}}']";
+        template = new Template("getNbr", "ran-network", xpathTemplate);
+    }
+
+    @Test
+    public void testExecuteTemplate() throws Exception {
+        final String resultString = "[{\"key\": \"value\"}]";
+        Mockito.when(cpsRestClient
+            .fetchNode("ran-network", "/ran-coverage-area/pLMNIdList[@mcc='310' and @mnc='410']"
+                + "/coverage-area[@coverageArea='Zone 1']"))
+            .thenReturn(resultString);
+        Mockito.when(templateRepository.findById(ArgumentMatchers.any()))
+            .thenReturn(Optional.of(template));
+        assertEquals(resultString,
+            executionBusinessLogic.executeTemplate("ran-network", "getNbr", request));
+
+        Mockito.when(templateRepository.findById(ArgumentMatchers.any()))
+            .thenReturn(Optional.empty());
+        exception.expect(RecordNotFoundException.class);
+        exception.expectMessage("Template does not exist");
+        executionBusinessLogic.executeTemplate("ran-network", "getNbr", request);
+
+    }
+
+    @Test
+    public void testExecuteTemplateException() throws Exception {
+        final String exceptionMessage = "Response from CPS other than 200: 404";
+        Mockito.when(cpsRestClient
+            .fetchNode("ran-network", "/ran-coverage-area/pLMNIdList[@mcc='310' and @mnc='410']"
+                + "/coverage-area[@coverageArea='Zone 1']"))
+            .thenThrow(new CpsException(exceptionMessage));
+        Mockito.when(templateRepository.findById(ArgumentMatchers.any()))
+            .thenReturn(Optional.of(template));
+        exception.expect(ExecuteException.class);
+        exception.expectMessage(exceptionMessage);
+        executionBusinessLogic.executeTemplate("ran-network", "getNbr", request);
+
+        final Template template1 = new Template("getNbr", "ran-net", "sample");
+        Mockito.when(templateRepository.findById(ArgumentMatchers.any()))
+            .thenReturn(Optional.of(template1));
+        exception.expect(ExecuteException.class);
+        exception.expectMessage("Anchor not found for the schema");
+        executionBusinessLogic.executeTemplate("ran-net", "getNbr", request);
+
+    }
+
+    @Test
+    public void testExecuteTemplateNoAnchor() {
+        final Template template = new Template("getNbr", "ran-net", "sample");
+        Mockito.when(templateRepository.findById(ArgumentMatchers.any()))
+            .thenReturn(Optional.of(template));
+        exception.expect(ExecuteException.class);
+        exception.expectMessage("Anchor not found for the schema");
+        executionBusinessLogic.executeTemplate("ran-net", "getNbr", request);
+    }
+
+}
diff --git a/src/test/java/org/onap/cps/tdmt/service/TemplateBusinessLogicTest.java b/src/test/java/org/onap/cps/tdmt/service/TemplateBusinessLogicTest.java
new file mode 100644 (file)
index 0000000..1f3fee9
--- /dev/null
@@ -0,0 +1,116 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP
+ * ================================================================================
+ * Copyright (C) 2021 Wipro Limited.
+ * ================================================================================
+ * 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
+ *
+ *      http://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.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.cps.tdmt.service;
+
+import static org.junit.Assert.assertEquals;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Optional;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.ExpectedException;
+import org.junit.runner.RunWith;
+import org.mockito.ArgumentMatchers;
+import org.mockito.Mockito;
+import org.onap.cps.tdmt.db.TemplateRepository;
+import org.onap.cps.tdmt.exception.RecordNotFoundException;
+import org.onap.cps.tdmt.model.Template;
+import org.onap.cps.tdmt.model.TemplateId;
+import org.onap.cps.tdmt.model.TemplateRequest;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.TestConfiguration;
+import org.springframework.boot.test.mock.mockito.MockBean;
+import org.springframework.context.annotation.Bean;
+import org.springframework.test.context.junit4.SpringRunner;
+
+@RunWith(SpringRunner.class)
+public class TemplateBusinessLogicTest {
+
+    @TestConfiguration
+    static class TemplateBusinessLogicTestContextConfiguration {
+
+        @Bean
+        public TemplateBusinessLogic templateBusinessLogic() {
+            return new TemplateBusinessLogic();
+        }
+    }
+
+    @Autowired
+    private TemplateBusinessLogic templateBusinessLogic;
+
+    @MockBean
+    private TemplateRepository templateRepository;
+
+    @Rule
+    public ExpectedException exception = ExpectedException.none();
+
+    private Template template;
+    private TemplateId templateId;
+
+    @Before
+    public void setup() {
+        template = new Template("getNbr", "ran-network", "sample");
+        final TemplateId templateId = new TemplateId("getNbr", "ran-network");
+    }
+
+    @Test
+    public void testCreateTemplate() throws Exception {
+        final TemplateRequest templateRequest = new TemplateRequest("getNbr", "ran-network", "sample");
+        Mockito.when(templateRepository.save(ArgumentMatchers.any())).thenReturn(template);
+        assertEquals(template, templateBusinessLogic.createTemplate(templateRequest));
+    }
+
+    @Test
+    public void testGetAllTemplates() throws Exception {
+        final List<Template> templates = new ArrayList<>();
+        templates.add(template);
+        Mockito.when(templateRepository.findAll()).thenReturn(templates);
+        assertEquals(templates, templateBusinessLogic.getAllTemplates());
+    }
+
+    @Test
+    public void testGetTemplate() throws Exception {
+        Mockito.when(templateRepository.findById(templateId)).thenReturn(Optional.of(template));
+        assertEquals(template, templateBusinessLogic.getTemplate(templateId));
+
+        Mockito.when(templateRepository.findById(ArgumentMatchers.any()))
+            .thenReturn(Optional.empty());
+        exception.expect(RecordNotFoundException.class);
+        exception.expectMessage("Template not found for given id and schema");
+        templateBusinessLogic.getTemplate(new TemplateId("getNbr", "empty-schema"));
+    }
+
+    @Test
+    public void testDeleteTemplate() throws Exception {
+        Mockito.when(templateRepository.existsById(templateId)).thenReturn(true);
+        templateBusinessLogic.deleteTemplate(templateId);
+        verify(templateRepository, times(1)).deleteById(templateId);
+
+        Mockito.when(templateRepository.existsById(ArgumentMatchers.any())).thenReturn(false);
+        exception.expect(RecordNotFoundException.class);
+        exception.expectMessage("Delete failed. Could not find template with specified id");
+        templateBusinessLogic.deleteTemplate(new TemplateId("getNbr", "empty-schema"));
+    }
+}
diff --git a/src/test/resources/application-test.properties b/src/test/resources/application-test.properties
new file mode 100644 (file)
index 0000000..c4daedd
--- /dev/null
@@ -0,0 +1,3 @@
+app.xnfProxyUrl=http://localhost:8000/
+app.schemaToAnchor.ran-coverage-area=coverage-area-onap
+app.schemaToAnchor.ran-network=ran-network
\ No newline at end of file