2019/11

Optional을 어떻게 하면 효율적으로 사용할 수 있을까? 전통적인 null check 코드를 살펴보자 NullPointException 방어패턴 중첩 null 체크 if(a != null){ B b = a.getMember(); if(b != null){ C c = b.getAddress()); if(c != null){ ... } } } return "incheon"; return 하기 if(a == null) return "incheon"; B b = a.getMember(); if(b == null) return "incheon"; C c = b.getAddress(); ... 어떻게 하면 null처리를 효과적으로 어떻게 할 수 있을까? Optional 자바8에는 Optional이라는 것이 생겼..
Mockito 관련 어노테이션 @RunWith(MockitoJunitRunner.class) Mockito에서 제공하는 목객체를 사용하기 하기위해 위와같은 어노테이션을 테스트클래스에 달아준다. @RunWith(MockitoJunitRunner.class) public class Test(){ ... } ⇒ 꼭 달아줘야하는건 아니지만, 이 어노테이션을 달지 않으면 아래와 같은 작업이 필요하다. publc class Test(){ @Before public void setUp(){ MockitoAnnotations.initMocks(this); } } @Mock mock 객체를 생성한다. @InjectMocks @InjectMocks라는 어노테이션이 존재하는데, @Mock이 붙은 목객체를 @InjectMoc..
프로퍼티 우선순위 유저 홈 디렉토리에 있는 spring-boot-dev-tools.properties 테스트에 있는 @TestPropertySource @SpringBootTest 애노테이션의 properties 애트리뷰트 커맨드 라인 아규먼트 SPRING_APPLICATION_JSON (환경 변수 또는 시스템 프로티) 에 들어있는 프로퍼티 ServletConfig 파라미터 ServletContext 파라미터 java:comp/env JNDI 애트리뷰트 System.getProperties() 자바 시스템 프로퍼티 OS 환경 변수 RandomValuePropertySource JAR 밖에 있는 특정 프로파일용 application properties JAR 안에 있는 특정 프로파일용 application..
@Conditional spring4 부터 사용가능하며, Java configuration에서 조건적으로 Spring Bean을 등록할 수 있다. @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE, ElementType.METHOD}) public @interface Conditional { /** * All {@link Condition}s that must {@linkplain Condition#matches match} * in order for the component to be registered. */ Class? extends Condition[] value(); } // Condtion.class public interface C..
Junit 프레임워크에서 많이사용되는 모키토 프레임워크에 대해 알아보자. 차별점 테스트 그 자체에 집중한다. 테스트 스텁을 만드는 것과 검증을 분리시켰다. Mock 만드는 방법을 단일화했다. 테스트 스텁을 만들기 쉽다. API가 간단하다. 프레임워크가 지원해주지 않으면 안되는 코드를 최대한 배제했다. 실패 시에 발생하는 에러추적이 깔끔하다. 환경구성 org.mockito mockito-all 1.9.5 test 기본 사용법 Mockito는 Stub 작성과 Verify가 중심을 이루며 다음과 같은 순서로 진행된다. CreateMock : 인터페이스에 해당하는 Mock 객체를 만든다. Stub : 테스트에 필요한 Mock 객체의 동작을 지정한다.(필요시만) Exercise : 테스트 메소드 내에서 Mock객..
Type별로 중요한 matcher들을 정리 Core anything describedAs is Logical allOf : 모든 조건 만족시 참 (like Java &&) anyOf : 조건 중 하나 만족시 참 (like Java ||) not : 비교 결과 부정 또는 다름 Objects equalTo hasToString instanceOf, isCompatibleType notNullValue, nullValue sameInstance Numbers closeTo greaterThan, greaterThanOrEqualTo, lessThan, lessThanOrEqualTo Beans hasProperty Collections array hasEntry, hasKey, hasValue hasItem,..
Junit을 사용할 때 Hamcrest 프레임워크를 사용하면 가독성은 물론이고 코드의 조건을 조금 더 손쉽게 확인할 수 있다. Hamcrest란? Hamcrest는 소프트웨어 테스트를 위한 framework. 기존의 matchers 클래스를 통해 코드의 조건을 확인할 수 있음 Junit에서 Hamcrest matcher를 사용하려면 assertThat 문 뒤에 하나 또는 여러 개의 matchers를 사용한다. ⇒ Hamcrest는 최대한 가독성이 있는 test scripts를 가지는 것을 목표로 하고 있음 boolean a; boolean b; assertThat(a, equalTo(b)); assertThat(a, is(equalTo(b)); assertThat(a, is(b)); // is 메소드는 ..
배너를 만드는법 1. org.springframework.boot.Banner 인터페이스를 구현하여 custom banner 개발 @SpringBootApplication public class SampleApplication { public static void main(String[] args) { SpringApplication springApplication = new SpringApplication(SampleApplication.class); springApplication.setBanner((environment, sourceClass, out)->{ out.println("Spring Boot! Corn!"); }); springApplication.run(args); } } 하지만.. 단..
1. 의존성 추가 org.springframework.boot spring-boot-starter-freemarker 2. freemarker template 작성 /src/main/resource/templates 경로에 hello.ftl 작성 This is freemarker sample. ${message} 3. Controller 작성 @Controller public class FreemarkerController { @GetMapping("/welcome") public String hello(Map model){ model.put("message", "hello freemarker!"); return "hello"; } }4. properties 설정 spring.freemarker.temp..
ServletRegistrationBean, FilterRegistrationBean, ServletListenerRegistrationBean을 이용해서 등록할 수 있다. 1. 필터 생성 및 등록 LogFilter1 public class LogFilter1 extends GenericFilterBean { private static final Logger log = LoggerFactory.getLogger(LogFilter1.class); @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, Servlet..
깡냉쓰
'2019/11 글 목록