티스토리 뷰

Dev/Spring

Spring Boot II - Profiles, Unit Tests

마이스토리 2016. 6. 1. 10:25

> Using Profiles and Properties to Create Enviroment-Specific Runtime Configurations

> profile을 적용하고자 하는 bean에 @Profile 어노테이션 추가
@Component
@Profile("batch")
public class GreetingBatchBean {


> jar application 구동 시 --spring.profiles.active=batch 옵션 추가

java -jar application.jar --spring.profiles.active=batch


> eclipse에서 maven으로 구동시

 - Run As > Maven Build ... 

 - Goals : spring-boot:run

 - Enviroment : 추가 ( Variable - spring.profile.active, Value - batch )


> profile별 properties 설정 및 적용

> profile별 properties 파일 생성 : ex) application-프로파일명.xml
[application-batch.properties]
##
# The Batch Application Configuration File
#
# This file is included when the 'batch' Spring profile is active
##

##
# Greeting Scheduled Process Configuration
##
batch.greeting.cron=0,30 * * * * *
batch.greeting.initialDelay=5000
batch.greeting.fixedRate=15000
batch.greeting.fixedDelay=15000


> 사용할 빈에서 프로퍼티값 적용: ${property anme}

@Component

@Profile("batch")

public class GreetingBatchBean {


@Scheduled(cron="${batch.greeting.cron}")

      public void cronJob(){


@Scheduled(initialDelayString = "${batch.greeting.initialDelay}"

, fixedRateString = "${batch.greeting.fixedRate}" //이전 수행 시작 기준. 이전 배치가 완료되어야 다음 배치 실행됨.

, fixedDelayString = "${batch.greeting.fixedDelay}" //이전 수행 종료 기준.

)

public void fixedRateJobWithInitialDelay(){



> base property file 에 활성화할 프로파일 지정: application.properties

##

# The Base Application Configuration File

##


##

# Profile Configuration

#   available profiles : batch

##

spring.profiles.active=batch


> spring.profiles.active 환경변수가 command line 옵션과 application.properties에 중복될 경우에는 command line 옵션이 적용됨.


> Creating Unit Tests with Spring Boot

> pom.xml 추가
    <!-- unit test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>


> Base Unit Test Abstarct클래스를 작성 : 모든 JUnit 테스트클래스의 Base

@RunWith(SpringJUnit4ClassRunner.class)

@SpringApplicationConfiguration(classes = SampleSpringBootApplication.class)

public abstract class SampleSpringBootApplicationTests {


protected Logger logger = LoggerFactory.getLogger(this.getClass());

}


> 테스트 클래스 작성

@Transactional

public class GreetingServiceTest extends SampleSpringBootApplicationTests {


@Autowired

private GreetingService greetingService;

@Before

public void setUp() throws Exception {

greetingService.evictCache();

}


@After

public void tearDown() throws Exception {

//clean up after each test method

}


@Test

public void testFindAll() {

Collection<Greeting> list = service.findAll();

Assert.assertNotNull("failure - expected not null", list);

Assert.assertEquals("failure - expected size", 2, list.size());

}

@Test

public void testFindOne(){

BigInteger id = new BigInteger("1");

Greeting entity = service.findOne(id);

Assert.assertNotNull("failure - expected not null", entity);

Assert.assertEquals("failure - expected id attribute match", id, entity.getId());

}

@Test

public void testFindOneNotFound(){

BigInteger id = new BigInteger("100");

Greeting entity = service.findOne(id);

Assert.assertNull("failure - expected null", entity);

}

@Test

public void testCreate(){

Greeting entity = new Greeting();

entity.setText("test");

Greeting createdEntity = service.create(entity);

Assert.assertNotNull("failure - expected not null", createdEntity);

Assert.assertNotNull("failure - expected id attribute not null", createdEntity.getId());

Assert.assertEquals("failure - expected text attribute match", "test", createdEntity.getText());

Collection<Greeting> list = service.findAll();

Assert.assertEquals("failure - expected size", 3, list.size());

}

@Test

public void testCreateWithId(){

Exception e = null;

Greeting entity = new Greeting();

entity.setId(BigInteger.TEN);

entity.setText("test");

try {

service.create(entity);

} catch (EntityExistsException eee) {

e = eee;

}

Assert.assertNotNull("failure - expected exception", e);

Assert.assertTrue("failure - expected EntityExistsExcepion", e instanceof EntityExistsException);

}

@Test

public void testUpdate(){

BigInteger id = new BigInteger("1");

Greeting entity = service.findOne(id);

Assert.assertNotNull("failure - expected not null", entity);

String updatedText = entity.getText() + " test";

entity.setText(updatedText);

Greeting updatedEntity = service.update(entity);

Assert.assertNotNull("failure - expected updated entity not null", updatedEntity);

Assert.assertEquals("failure - expected updated entity id attribute unchanged", id, updatedEntity.getId());

Assert.assertEquals("failuer - expected updated entity text attribute match", updatedText, updatedEntity.getText());

}

@Test

public void testUpdatedNotFound(){

Exception e = null;

Greeting entity = new Greeting();

entity.setId(BigInteger.TEN);

entity.setText("test");

try {

service.update(entity);

} catch (NoResultException re) {

e = re;

}

Assert.assertNotNull("failure - expected exception", e);

Assert.assertTrue("failure - expected EntityExistsExcepion", e instanceof NoResultException);

}

@Test

public void testDelete(){

BigInteger id = new BigInteger("1");

Greeting entity = service.findOne(id);

Assert.assertNotNull("failure - expected not null", entity);

service.delete(id);

Collection<Greeting> list = service.findAll();

Assert.assertEquals("failure - expected size", 1, list.size());

Greeting deletedEntity = service.findOne(id);

Assert.assertNotEquals("failure - expected entity to be deleted", deletedEntity);

}

}


> mvn 실행 시 test 단계를 생략하려면 -DskipTests 옵션 추가

> mvn clean package -DskipTests


> Web Service Controller Unit Tests With Spring Boot

> abstract controller test 클래스 작성 : 

* 기본 application test 클래스상속하여 작성, 

* 다른 컨터롤터 테스트 클래스들이 이 abstarct클래스를  상속하여 만들어짐

import java.io.IOException;


import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.test.context.web.WebAppConfiguration;

import org.springframework.test.web.servlet.MockMvc;

import org.springframework.test.web.servlet.setup.MockMvcBuilders;

import org.springframework.web.context.WebApplicationContext;


import com.fasterxml.jackson.core.JsonParseException;

import com.fasterxml.jackson.core.JsonProcessingException;

import com.fasterxml.jackson.databind.JsonMappingException;

import com.fasterxml.jackson.databind.ObjectMapper;


@WebAppConfiguration

public abstract class AbstractControllerTest extends AbstractTest {


protected MockMvc mvc;

@Autowired

protected WebApplicationContext webApplicationContext;

protected void setUp(){

mvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();

}

protected String mapToJson(Object obj) throws JsonProcessingException{

ObjectMapper mapper = new ObjectMapper();

return mapper.writeValueAsString(obj);

}

protected <T> T mapFromJson(String json, Class<T> clazz) throws JsonParseException, JsonMappingException, IOException {

ObjectMapper mapper = new ObjectMapper();

return mapper.readValue(json, clazz); 

}

}


> Controller test class 작성

package lyj.sample.web;


import java.math.BigInteger;


import org.junit.Assert;

import org.junit.Before;

import org.junit.Test;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.http.MediaType;

import org.springframework.test.web.servlet.MvcResult;

import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;

import org.springframework.transaction.annotation.Transactional;


import lyj.sample.AbstractControllerTest;

import lyj.sample.model.Greeting;

import lyj.sample.service.GreetingService;


@Transactional

public class GreetingControllerTest extends AbstractControllerTest {


@Autowired

private GreetingService greetingService;


@Before

public void setUp() {

super.setUp();

greetingService.evictCache();

}


@Test

public void testGetGreetings() throws Exception {


String uri = "/api/greetings";


MvcResult result = mvc.perform(

MockMvcRequestBuilders.get(uri).accept(

MediaType.APPLICATION_JSON)).andReturn();


String content = result.getResponse().getContentAsString();

int status = result.getResponse().getStatus();


Assert.assertEquals("failure- expected HTTP status 200", 200, status);

Assert.assertTrue(

"failure - expected HTTP response body to have a value",

content.trim().length() > 0);


}


@Test

public void testGetGreeting() throws Exception {


String uri = "/api/greetings/{id}";

Long id = new Long(1);


MvcResult result = mvc.perform(

MockMvcRequestBuilders.get(uri, id).accept(

MediaType.APPLICATION_JSON)).andReturn();


String content = result.getResponse().getContentAsString();

int status = result.getResponse().getStatus();


Assert.assertEquals("failure - expected HTTP status 200", 200, status);

Assert.assertTrue(

"failure - expected HTTP response body to have a value",

content.trim().length() > 0);


}


@Test

public void testGetGreetingNotFound() throws Exception {


String uri = "/api/greetings/{id}";

Long id = Long.MAX_VALUE;


MvcResult result = mvc.perform(

MockMvcRequestBuilders.get(uri, id).accept(

MediaType.APPLICATION_JSON)).andReturn();


String content = result.getResponse().getContentAsString();

int status = result.getResponse().getStatus();


Assert.assertEquals("failure - expected HTTP status 404", 404, status);

Assert.assertTrue("failure - expected HTTP response body to be empty",

content.trim().length() == 0);


}


@Test

public void testCreateGreeting() throws Exception {


String uri = "/api/greetings";

Greeting greeting = new Greeting();

greeting.setText("test");

String inputJson = super.mapToJson(greeting);


MvcResult result = mvc.perform(

MockMvcRequestBuilders.post(uri)

.contentType(MediaType.APPLICATION_JSON)

.accept(MediaType.APPLICATION_JSON).content(inputJson))

.andReturn();


String content = result.getResponse().getContentAsString();

int status = result.getResponse().getStatus();


Assert.assertEquals("failure - expected HTTP status 201", 201, status);

Assert.assertTrue(

"failure - expected HTTP response body to have a value",

content.trim().length() > 0);


Greeting createdGreeting = super.mapFromJson(content, Greeting.class);


Assert.assertNotNull("failure - expected greeting not null",

createdGreeting);

Assert.assertNotNull("failure - expected greeting.id not null",

createdGreeting.getId());

Assert.assertEquals("failure - expected greeting.text match", "test",

createdGreeting.getText());


}


@Test

public void testUpdateGreeting() throws Exception {


String uri = "/api/greetings/{id}";

BigInteger id = new BigInteger("1");

Greeting greeting = greetingService.findOne(id);

String updatedText = greeting.getText() + " test";

greeting.setText(updatedText);

String inputJson = super.mapToJson(greeting);


MvcResult result = mvc.perform(

MockMvcRequestBuilders.put(uri, id)

.contentType(MediaType.APPLICATION_JSON)

.accept(MediaType.APPLICATION_JSON).content(inputJson))

.andReturn();


String content = result.getResponse().getContentAsString();

int status = result.getResponse().getStatus();


Assert.assertEquals("failure - expected HTTP status 200", 200, status);

Assert.assertTrue(

"failure - expected HTTP response body to have a value",

content.trim().length() > 0);


Greeting updatedGreeting = super.mapFromJson(content, Greeting.class);


Assert.assertNotNull("failure - expected greeting not null",

updatedGreeting);

Assert.assertEquals("failure - expected greeting.id unchanged",

greeting.getId(), updatedGreeting.getId());

Assert.assertEquals("failure - expected updated greeting text match",

updatedText, updatedGreeting.getText());


}


@Test

public void testDeleteGreeting() throws Exception {


String uri = "/api/greetings/{id}";

BigInteger id = new BigInteger("1");


MvcResult result = mvc.perform(

MockMvcRequestBuilders.delete(uri, id).contentType(

MediaType.APPLICATION_JSON)).andReturn();


String content = result.getResponse().getContentAsString();

int status = result.getResponse().getStatus();


Assert.assertEquals("failure - expected HTTP status 204", 204, status);

Assert.assertTrue("failure - expected HTTP response body to be empty",

content.trim().length() == 0);


Greeting deletedGreeting = greetingService.findOne(id);


Assert.assertNull("failure - expected greeting to be null",

deletedGreeting);


}

}


> Web Service Controller Unit Tests with Mockito and Spring Boot

> abstarct Test Class의 setUp 메소드 추가.
* BaseController는 빈 class이고 개별 Controller 클래스가 상속함.
protected void setUp(BaseController controller){
mvc = MockMvcBuilders.standaloneSetup(controller).build();
}

> Mockito Test class 작성
package lyj.sample.web;

import static org.mockito.Matchers.any;
import static org.mockito.Mockito.*;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collection;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.transaction.annotation.Transactional;

import lyj.sample.AbstractControllerTest;
import lyj.sample.model.Greeting;
import lyj.sample.service.EmailService;
import lyj.sample.service.GreetingService;

@Transactional
public class GreetingControllerMocksTest extends AbstractControllerTest {

@Mock
private EmailService emailService;

@Mock
private GreetingService greetingService;

@InjectMocks
private GreetingController controller;

@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
setUp(controller);
}

@Test
public void testGetGreetings() throws Exception {

// Create some test data
Collection<Greeting> list = getEntityListStubData();

// Stub the GreetingService.findAll method return value
when(greetingService.findAll()).thenReturn(list);

// Perform the behavior being tested
String uri = "/api/greetings";

MvcResult result = mvc.perform(
MockMvcRequestBuilders.get(uri).accept(
MediaType.APPLICATION_JSON)).andReturn();

// Extract the response status and body
String content = result.getResponse().getContentAsString();
int status = result.getResponse().getStatus();

// Verify the GreetingService.findAll method was invoked once
verify(greetingService, times(1)).findAll();

// Perform standard JUnit assertions on the response
Assert.assertEquals("failure - expected HTTP status 200", 200, status);
Assert.assertTrue(
"failure - expected HTTP response body to have a value",
content.trim().length() > 0);

}
@Test
    public void testGetGreeting() throws Exception {

        // Create some test data
        BigInteger id = new BigInteger("1");
        Greeting entity = getEntityStubData();

        // Stub the GreetingService.findOne method return value
        when(greetingService.findOne(id)).thenReturn(entity);

        // Perform the behavior being tested
        String uri = "/api/greetings/{id}";

        MvcResult result = mvc.perform(MockMvcRequestBuilders.get(uri, id)
                .accept(MediaType.APPLICATION_JSON)).andReturn();

        // Extract the response status and body
        String content = result.getResponse().getContentAsString();
        int status = result.getResponse().getStatus();

        // Verify the GreetingService.findOne method was invoked once
        verify(greetingService, times(1)).findOne(id);

        // Perform standard JUnit assertions on the test results
        Assert.assertEquals("failure - expected HTTP status 200", 200, status);
        Assert.assertTrue(
                "failure - expected HTTP response body to have a value",
                content.trim().length() > 0);
    }

    @Test
    public void testGetGreetingNotFound() throws Exception {

        // Create some test data
    BigInteger id = new BigInteger("999");

        // Stub the GreetingService.findOne method return value
        when(greetingService.findOne(id)).thenReturn(null);

        // Perform the behavior being tested
        String uri = "/api/greetings/{id}";

        MvcResult result = mvc.perform(MockMvcRequestBuilders.get(uri, id)
                .accept(MediaType.APPLICATION_JSON)).andReturn();

        // Extract the response status and body
        String content = result.getResponse().getContentAsString();
        int status = result.getResponse().getStatus();

        // Verify the GreetingService.findOne method was invoked once
        verify(greetingService, times(1)).findOne(id);

        // Perform standard JUnit assertions on the test results
        Assert.assertEquals("failure - expected HTTP status 404", 404, status);
        Assert.assertTrue("failure - expected HTTP response body to be empty",
                content.trim().length() == 0);

    }

    @Test
    public void testCreateGreeting() throws Exception {

        // Create some test data
        Greeting entity = getEntityStubData();

        // Stub the GreetingService.create method return value
        when(greetingService.create(any(Greeting.class))).thenReturn(entity);

        // Perform the behavior being tested
        String uri = "/api/greetings";
        String inputJson = super.mapToJson(entity);

        MvcResult result = mvc
                .perform(MockMvcRequestBuilders.post(uri)
                        .contentType(MediaType.APPLICATION_JSON)
                        .accept(MediaType.APPLICATION_JSON).content(inputJson))
                .andReturn();

        // Extract the response status and body
        String content = result.getResponse().getContentAsString();
        int status = result.getResponse().getStatus();

        // Verify the GreetingService.create method was invoked once
        verify(greetingService, times(1)).create(any(Greeting.class));

        // Perform standard JUnit assertions on the test results
        Assert.assertEquals("failure - expected HTTP status 201", 201, status);
        Assert.assertTrue(
                "failure - expected HTTP response body to have a value",
                content.trim().length() > 0);

        Greeting createdEntity = super.mapFromJson(content, Greeting.class);

        Assert.assertNotNull("failure - expected entity not null",
                createdEntity);
        Assert.assertNotNull("failure - expected id attribute not null",
                createdEntity.getId());
        Assert.assertEquals("failure - expected text attribute match",
                entity.getText(), createdEntity.getText());
    }

    @Test
    public void testUpdateGreeting() throws Exception {

        // Create some test data
        Greeting entity = getEntityStubData();
        entity.setText(entity.getText() + " test");
        Long id = new Long(1);

        // Stub the GreetingService.update method return value
        when(greetingService.update(any(Greeting.class))).thenReturn(entity);

        // Perform the behavior being tested
        String uri = "/api/greetings/{id}";
        String inputJson = super.mapToJson(entity);

        MvcResult result = mvc
                .perform(MockMvcRequestBuilders.put(uri, id)
                        .contentType(MediaType.APPLICATION_JSON)
                        .accept(MediaType.APPLICATION_JSON).content(inputJson))
                .andReturn();

        // Extract the response status and body
        String content = result.getResponse().getContentAsString();
        int status = result.getResponse().getStatus();

        // Verify the GreetingService.update method was invoked once
        verify(greetingService, times(1)).update(any(Greeting.class));

        // Perform standard JUnit assertions on the test results
        Assert.assertEquals("failure - expected HTTP status 200", 200, status);
        Assert.assertTrue(
                "failure - expected HTTP response body to have a value",
                content.trim().length() > 0);

        Greeting updatedEntity = super.mapFromJson(content, Greeting.class);

        Assert.assertNotNull("failure - expected entity not null",
                updatedEntity);
        Assert.assertEquals("failure - expected id attribute unchanged",
                entity.getId(), updatedEntity.getId());
        Assert.assertEquals("failure - expected text attribute match",
                entity.getText(), updatedEntity.getText());

    }

    @Test
    public void testDeleteGreeting() throws Exception {

        // Create some test data
        BigInteger id = new BigInteger("1");

        // Perform the behavior being tested
        String uri = "/api/greetings/{id}";

        MvcResult result = mvc.perform(MockMvcRequestBuilders.delete(uri, id))
                .andReturn();

        // Extract the response status and body
        String content = result.getResponse().getContentAsString();
        int status = result.getResponse().getStatus();

        // Verify the GreetingService.delete method was invoked once
        verify(greetingService, times(1)).delete(id);

        // Perform standard JUnit assertions on the test results
        Assert.assertEquals("failure - expected HTTP status 204", 204, status);
        Assert.assertTrue("failure - expected HTTP response body to be empty",
                content.trim().length() == 0);

    }

private Collection<Greeting> getEntityListStubData() {
Collection<Greeting> list = new ArrayList<Greeting>();
list.add(getEntityStubData());
return list;
}

private Greeting getEntityStubData() {
Greeting entity = new Greeting();
entity.setId(new BigInteger("1"));
entity.setText("hello");
return entity;
}
}

* http://blog.jdm.kr/222


댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2025/01   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31