티스토리 뷰
> Using Profiles and Properties to Create Enviroment-Specific Runtime Configurations
> 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 설정 및 적용
> 사용할 빈에서 프로퍼티값 적용: ${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
> 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
- Total
- Today
- Yesterday