묻고 답해요
169만명의 커뮤니티!! 함께 토론해봐요.
인프런 TOP Writers
-
미해결Practical Testing: 실용적인 테스트 가이드
OrderRepositoryTest에서 발생한 에러
package sample.cafekiosk.spring.domain.order; @ActiveProfiles("test") @DataJpaTest class OrderRepositoryTest { @Autowired private OrderRepository orderRepository; @Autowired private ProductRepository productRepository; @DisplayName("특정 주문 상태에 따라 주문을 조회한다") @Test void findOrdersBy() { //given Product product1 = createProduct("아메리카노", 3000, HANDMADE, SELLING); Product product2 = createProduct("카페라떼", 4000, HANDMADE, SELLING); Product product3 = createProduct("카푸치노", 5000, HANDMADE, SELLING); List<Product> products = List.of(product1, product2, product3); LocalDateTime startTime = LocalDateTime.of(2023, 10, 19, 0, 0); LocalDateTime orderTime = LocalDateTime.of(2023, 10, 19, 10, 0); LocalDateTime endTime = LocalDateTime.of(2023, 10, 20, 0, 0); Order completedOrder = createOrder(orderTime, PAYMENT_COMPLETED, products); Order canceledOrder = createOrder(orderTime, CANCELED, products); // when List<Order> orders = orderRepository.findOrdersBy(startTime, endTime, PAYMENT_COMPLETED); // then assertThat(orders).hasSize(1) .extracting("id", "orderStatus", "totalPrice", "registeredDateTime") .containsExactlyInAnyOrder( tuple(1L, PAYMENT_COMPLETED, 12000, orderTime) ); } private Product createProduct(String name, int price, ProductType productType, ProductSellingStatus productSellingStatus) { Product product = Product.builder() .name(name) .price(price) .type(productType) .sellingStatus(productSellingStatus) .build(); return productRepository.save(product); } private Order createOrder(LocalDateTime now, OrderStatus orderStatus, List<Product> products) { Order order = Order.builder() .products(products) .orderStatus(orderStatus) .registeredDateTime(now) .build(); return orderRepository.save(order); } @DisplayName("찾고자 하는 시간 안에 있는 주문을 조회한다") @Test void findOrdersBy2() { //given Product product1 = createProduct("아메리카노", 3000, HANDMADE, SELLING); Product product2 = createProduct("카페라떼", 4000, HANDMADE, SELLING); Product product3 = createProduct("카푸치노", 5000, HANDMADE, SELLING); List<Product> products = List.of(product1, product2, product3); LocalDateTime startTime = LocalDateTime.of(2023, 10, 19, 0, 0); LocalDateTime orderTime = LocalDateTime.of(2023, 10, 19, 10, 0); LocalDateTime endTime = LocalDateTime.of(2023, 10, 20, 0, 0); LocalDateTime overTime = LocalDateTime.of(2023, 10, 20, 10, 0); Order completedOrder = createOrder(orderTime, PAYMENT_COMPLETED, products); Order overTimeOrder = createOrder(overTime, PAYMENT_COMPLETED, products); // when List<Order> orders = orderRepository.findOrdersBy(startTime, endTime, PAYMENT_COMPLETED); // then assertThat(orders).hasSize(1) .extracting("id", "orderStatus", "totalPrice", "registeredDateTime") .containsExactlyInAnyOrder( tuple(1L, PAYMENT_COMPLETED, 12000, orderTime) ); } }각각 Test 수행할 땐 정상적으로 잘 동작했습니다. 하지만, 같이 Test을 수행하는 경우 findOrdersBy()에서 아래와 같은 에러가 발생하고 있습니다2023-10-20 23:12:40.519 INFO 8704 --- [ main] o.s.t.c.transaction.TransactionContext : Began transaction (1) for test context [DefaultTestContext@1a6c1270 testClass = OrderRepositoryTest, testInstance = sample.cafekiosk.spring.domain.order.OrderRepositoryTest@2d114d27, testMethod = findOrdersBy@OrderRepositoryTest, testException = [null], mergedContextConfiguration = [MergedContextConfiguration@18a136ac testClass = OrderRepositoryTest, locations = '{}', classes = '{class sample.cafekiosk.spring.CafeKioskApplication}', contextInitializerClasses = '[]', activeProfiles = '{test}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.autoconfigure.OverrideAutoConfigurationContextCustomizerFactory$DisableAutoConfigurationContextCustomizer@560348e6, org.springframework.boot.test.autoconfigure.actuate.metrics.MetricsExportContextCustomizerFactory$DisableMetricExportContextCustomizer@6f1c29b7, org.springframework.boot.test.autoconfigure.filter.TypeExcludeFiltersContextCustomizer@351584c0, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@fb58afcf, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@7b7fdc8, [ImportsContextCustomizer@77d67cf3 key = [org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration, eJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@27d5a580, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.context.SpringBootTestArgs@1, org.springframework.boot.test.context.SpringBootTestWebEnvironment@0], contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]], attributes = map['org.springframework.test.context.event.ApplicationEventsTestExecutionListener.recordApplicationEvents' -> false]]; transaction manager [org.springframework.orm.jpa.JpaTransactionManager@40d10264]; rollback [true] Hibernate: insert into product (id, created_date_time, modified_date_time, name, price, product_number, selling_status, type) values (default, ?, ?, ?, ?, ?, ?, ?) Hibernate: insert into product (id, created_date_time, modified_date_time, name, price, product_number, selling_status, type) values (default, ?, ?, ?, ?, ?, ?, ?) Hibernate: insert into product (id, created_date_time, modified_date_time, name, price, product_number, selling_status, type) values (default, ?, ?, ?, ?, ?, ?, ?) Hibernate: insert into orders (id, created_date_time, modified_date_time, order_status, registered_date_time, total_price) values (default, ?, ?, ?, ?, ?) Hibernate: insert into order_product (id, created_date_time, modified_date_time, order_id, product_id) values (default, ?, ?, ?, ?) Hibernate: insert into order_product (id, created_date_time, modified_date_time, order_id, product_id) values (default, ?, ?, ?, ?) Hibernate: insert into order_product (id, created_date_time, modified_date_time, order_id, product_id) values (default, ?, ?, ?, ?) Hibernate: insert into orders (id, created_date_time, modified_date_time, order_status, registered_date_time, total_price) values (default, ?, ?, ?, ?, ?) Hibernate: insert into order_product (id, created_date_time, modified_date_time, order_id, product_id) values (default, ?, ?, ?, ?) Hibernate: insert into order_product (id, created_date_time, modified_date_time, order_id, product_id) values (default, ?, ?, ?, ?) Hibernate: insert into order_product (id, created_date_time, modified_date_time, order_id, product_id) values (default, ?, ?, ?, ?) Hibernate: select order0_.id as id1_2_, order0_.created_date_time as created_2_2_, order0_.modified_date_time as modified3_2_, order0_.order_status as order_st4_2_, order0_.registered_date_time as register5_2_, order0_.total_price as total_pr6_2_ from orders order0_ where order0_.registered_date_time>=? and order0_.registered_date_time<? and order0_.order_status=? 2023-10-20 23:12:40.621 INFO 8704 --- [ main] o.s.t.c.transaction.TransactionContext : Rolled back transaction for test: [DefaultTestContext@1a6c1270 testClass = OrderRepositoryTest, testInstance = sample.cafekiosk.spring.domain.order.OrderRepositoryTest@2d114d27, testMethod = findOrdersBy@OrderRepositoryTest, testException = java.lang.AssertionError: [Extracted: id, orderStatus, totalPrice, registeredDateTime] Expecting actual: [(3L, PAYMENT_COMPLETED, 12000, 2023-10-19T10:00 (java.time.LocalDateTime))] to contain exactly in any order: [(1L, PAYMENT_COMPLETED, 12000, 2023-10-19T10:00 (java.time.LocalDateTime))] elements not found: [(1L, PAYMENT_COMPLETED, 12000, 2023-10-19T10:00 (java.time.LocalDateTime))] and elements not expected: [(3L, PAYMENT_COMPLETED, 12000, 2023-10-19T10:00 (java.time.LocalDateTime))] , mergedContextConfiguration = [MergedContextConfiguration@18a136ac testClass = OrderRepositoryTest, locations = '{}', classes = '{class sample.cafekiosk.spring.CafeKioskApplication}', contextInitializerClasses = '[]', activeProfiles = '{test}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTestContextBootstrapper=true}', contextCustomizers = 왜 id가 3인가요?? 저는 DataJpaTest을 수행하면 각각의 Test 마다 rollBack이 수행되어 id가 당연히 1이라고 생각했었습니다. 왜 3이 되는지 이해가 되지 않습니다
-
미해결Java/Spring 테스트를 추가하고 싶은 개발자들의 오답노트
SystemUuidHolder를 테스트하는 경우
Interface를 이용하여 완충재를 두고 테스트를 할 때는 테스트를 위한 mock 구현체를 이용하여 final 메소드를 stub하는 것을 피한다는 것은 이해를 했는데요. 갑자기 드는 생각이 결국 프로젝트가 배포될 때는 SystemUuidHolder라는 구현체를 사용하게 되고 그러면 해당 클래스의 대한 테스트도 진행해야 하나요? 진행한다면 해당 클래스는 UUID를 사용하고 있으니 final 메소드를 stub하는 상황을 피할 수 없게 되는건가요?
-
미해결Practical Testing: 실용적인 테스트 가이드
정적 팩터리 메서드 사용 기준?
제목 그대로 언제 사용하시는지에 대해 얘기를 나눠보고 싶어 질문 남깁니다.제 경우는 영속성 계층에 새로운 객체가 추가될 때 (RDB에 레코드를 추가할 때) new 키워드를 사용하여 id 값을 생성자로 받지 않는 생성자를 열어두고,존재하는 도메인 엔티티 혹은 영속성 엔티티를 영속성 계층으로부터 불러올 때는 정적 팩터리 메서드를 사용하는데강의를 진행하시면서 습관적으로 생성자 대신 static 메서드를 통해 생성 하시더라구요, 강사님만의 명확한 기준이 있으신지 궁금합니다.
-
미해결Practical Testing: 실용적인 테스트 가이드
ProductRepository에 @Repository 어노테이션을 붙인 이유
스프링 컨테이너가 뜰 때 Jpa의 Repository 인터페이스 하위 타입을 스캔하여 빈으로 등록하는 것으로 알고 있어서 ProductRepository가 자동으로 스캔이 될텐데 @Repository 어노테이션을 붙이신 이유가 궁금합니다
-
미해결Practical Testing: 실용적인 테스트 가이드
ProductNumberFactory 클래스는 어떤 Layer 객체로 봐야 할까요?
안녕하세요! 먼저 항상 좋은 강의 감사드립니다! 저도 작은 경험 이지만 개발을 하면서 서비스 단의 로직을 분리 (강의에서 말씀 해주신 것 처럼 책임을 분리할 정도)해야 하는 상황인 경우, 이렇게 하는게 맞는지는 모르겠으나, Point1. ServiceUtil 클래스를 정의하여 컴포넌트로 주입받아 사용하거나 (실무에선 이렇게 사용)Point2. 학습시에는 Facade 패턴을 이용하여 서로 다른 서비스들의 상위 퍼사드 객체를 만들어서 사용한 적이 있습니다.(물론 퍼사드 패턴의 경우, 두 로직이 완전히 다른 맥락인 경우에 사용하는 것 같습니다.. 강의 예제와 같이 결합도가 높은 경우가 아니라..)그런데, 강의에서는 Factory 객체를 만들어서 (마치 제가 ServiceUtil을 만들어서 사용하는 것 처럼 - 사실 이름만 다르지 같습니다)사용하시는 모습을 보여주셨는데, Q1. 강사님께서는 실무에서 서비스의 책임을 분리할 때 주로 이런식으로 Factory 클래스를 분리하여 사용하시는지 궁금하고, Q2.그렇게 Factory 클래스로 책임을 분리했을 때, 이 Factory 클래스는 Controller / Service/ Repository 그 어느것도 아니게 되는데, Spring WEB mvc 레이어 아키텍쳐 상으로 어떤 Layer의 어떤 입장의 객체로 인지하고 사용해야 하는지 여쭙고 싶습니다. 감사합니다.
-
미해결따라하며 배우는 리액트 A-Z[19버전 반영]
PostDetailPage params 이 어디서 온건가요?
async function PostDetailPage({ params }: any) { const post = await getPost(params.id); return ( <div> <h1>Posts/{post.id}</h1> <div> <h3>{post.title}</h3> <p>{post.created}</p> </div> </div> ); }PostDetailPage 에서 params을 콘솔에 출력하면 id값이 나오는거는 주소에서 받아오는건가요?
-
미해결Practical Testing: 실용적인 테스트 가이드
private method 테스트문의
안녕하세요. 좋은 강의 잘 듣고 있습니다 ^^ 강의에서 private method 테스트를 해야되는 상황이라면객체를 분리해야되는 상황이라고 말씀을 주셨는데실무에서는 꼭 분리를 해야되는 상황이 아닐수도 있을텐데1)실무에서는 private method 에 대한 테스트는 거의 작성안하나요? 2)레거시 프로젝트를 맡았을때 public method 에 대한 테스트를 작성하기에는 많은 작업이 필요하다면 private method 라도 테스트 코드를 작성하는게 좋을거 같은데 이런 경우도 작성을 안하나요?3) private 함수를 변경하는경우 해당함수만 테스트하고 싶을거 같은데 이런경우는 어떻게하나요?
-
미해결Practical Testing: 실용적인 테스트 가이드
controller, service dto 분리에대해 질문드립니다.
포스, 키오스크, 이외 다른 주문 엔드포인트로부터 주문이 들어왔을때 똑같은 서비스를 사용할 경우 그 서비스에서 사용하는 서비스dto로 변환해주어야 하기 때문에 컨트롤러 dto와 서비스dto를 분리해주는게 좋다로 이해했는데 맞을까요?
-
미해결[코드캠프] 부트캠프에서 만든 고농축 백엔드 코스
강의에 있는 똑같은 ppt는 pdf로라도 구할 수 없는걸가요?
강의자료에 자료가 있습니다만, 가르쳐주시는 곳의 ppt 랑 똑같은거는 아니더라고요. 강의중에 쓰는 ppt가 복습할때 더 효율적일 거 같아서 볼려고 하는데 볼 수 없을까요?
-
미해결따라하며 배우는 리액트 A-Z[19버전 반영]
netlify를 배포를 했는데 문제 생겼습니다
netlify를 배포 했는데 경고와 빌드 문제 인 것 같습니다 어떻게 하면 될까요?
-
해결됨Practical Testing: 실용적인 테스트 가이드
생성 post 요청 시 Response 객체 전달 이유
Order를 생성하면서 이에 대한 서비스 반환 값으로 orderResponse를 반환하는 것을 볼 수 있었습니다.얕은 지식으로는 Create에 해당하는 내용은 201 상태코드와 URI.Created 를 사용하여 헤더에 Location을 명시해주고 "/api/v1/orders/" + id형태로 제공해주는 것이 좋은 것으로 알고 있었는데 생성 시에도 반환 값을 제공해주시는 이유가 있을까요?
-
해결됨[코드캠프] 부트캠프에서 만든 고농축 백엔드 코스
회원가입 과제 정답지를 알고싶어여
파이널 과제말고 수업도중에 회원가입 과제가있는데 그거 정답지를 좀 알고싶어요
-
미해결Java/Spring 테스트를 추가하고 싶은 개발자들의 오답노트
FakeRepository 만들 때 Join 테이블하는 경우 질문드립니다.
서비스 테스트 시 Repository 상속해서 FakeRepository를 생성자 주입을 통해 진행한다는 내용에 대해서는 이해하고 실습해 보았습니다.그런데 만약 Repository 메서드 중 JPA의 on 절을 이용한 join을 사용해 데이터를 가져오는 경우 FakeRepository의 내부 구현이 궁금합니다내부에 Id와 List를 통해 해당 엔티티에 대한 정보를 저장할 수 있지만, Join을 하는 경우 외부 테이블의 정보가 필요하기 때문에 이를 Fake하고 싶을 때는 어떻게 해결할 수 있는지 알려주시면 감사하겠습니다.
-
해결됨Practical Testing: 실용적인 테스트 가이드
Beverage 인터페이스
테스트의 질문과는 좀 벗어나는 질문입니다만.. 궁금해서 여쭤보게 되었습니다!간단한 프로젝트를 구성하는 과정에서 Beverage라는 인터페이스를 만들어 추상화를 진행하고 해당 인터페이스는 get의 행위만 가지고 있었습니다.그리고 추가된 라떼와 아메리카노 둘 다 같은 속성이지만 구현을 통해서 두 개의 구성 클래스를 만들어 예제를 진행하였는데요.이에 다음과 같은 의문점이 생겼습니다.인터페이스가 get이라는 행위만 가져도 사용해도 괜찮은지. 지금과 같은 상황에서는 확장에서의 의미로 추상 클래스가 더 괜찮을 것 같은데 사용하지 않은 이유가 있으신지 궁금합니다ㅎㅎ좋은 강의 제공해주셔서 감사합니다~
-
해결됨[코드캠프] 부트캠프에서 만든 고농축 백엔드 코스
10월 30일 이후에 html과 javascript강의도 삭제 되나요??
10월 30일 이후에 html과 javascript강의도 삭제 되나요??
-
해결됨[코드캠프] 부트캠프에서 만든 고농축 백엔드 코스
post 요청시 헤더 관련 에러
post 요청시 헤더 관련 아래 에러 발생하는데, apollo-require-preflight: true등을 넣으면 정상 작동 하네요. 혹시 이 에러가 강의 중에는 안 나던데, 이유 알 수 있을까요? { "errors": [ { "message": "This operation has been blocked as a potential Cross-Site Request Forgery (CSRF). Please either specify a 'content-type' header (with a type that is not one of application/x-www-form-urlencoded, multipart/form-data, text/plain) or provide a non-empty value for one of the following headers: x-apollo-operation-name, apollo-require-preflight\n", "extensions": { "code": "BAD_REQUEST", "stacktrace": [ "BadRequestError: This operation has been blocked as a potential Cross-Site Request Forgery (CSRF). Please either specify a 'content-type' header (with a type that is not one of application/x-www-form-urlencoded, multipart/form-data, text/plain) or provide a non-empty value for one of the following headers: x-apollo-operation-name, apollo-require-preflight", "", " at new GraphQLErrorWithCode (/Users/hojeongpark/Develop/study/backend-bootcamp/class/section13/13-01-single-image-upload/node_modules/@apollo/server/src/internalErrorClasses.ts:15:5)", " at new BadRequestError (/Users/hojeongpark/Develop/study/backend-bootcamp/class/section13/13-01-single-image-upload/node_modules/@apollo/server/src/internalErrorClasses.ts:116:5)", " at preventCsrf (/Users/hojeongpark/Develop/study/backend-bootcamp/class/section13/13-01-single-image-upload/node_modules/@apollo/server/src/preventCsrf.ts:91:9)", " at ApolloServer.executeHTTPGraphQLRequest (/Users/hojeongpark/Develop/study/backend-bootcamp/class/section13/13-01-single-image-upload/node_modules/@apollo/server/src/ApolloServer.ts:1047:20)", " at processTicksAndRejections (node:internal/process/task_queues:95:5)" ] } } ] }
-
미해결따라하며 배우는 리액트 A-Z[19버전 반영]
Netlify 배포 가능할까요?
혹시 넷플릭스로 Netlify 배포 가능할까요?
-
미해결Practical Testing: 실용적인 테스트 가이드
Repository 구현시 @Repository 어노테이션을 붙이는 이유가 궁금합니다.
안녕하세요, 우빈님 너무 좋은 강의를 올려주셔서 잘 듣고 있습니다! Repository 구현 시 @Repository 어노테이션을 붙이는 이유가 궁금합니다.스프링 데이터 JPA를 사용할 경우 스프링이 만들어서 제공하는 컴포넌트를 사용해서 @Repository 를 생략해도 되는 거로 알고 있는데, 사용하시는 이유가 따로 있는지 궁금합니다.
-
해결됨[코드캠프] 부트캠프에서 만든 고농축 백엔드 코스
queryRunner fineOne 리턴타입
queryRunner.manager.findOne의 리턴 타입이 {id: string} | null 로 추론되는데 저만 이렇게 추론되는 걸까요? (webstorm 사용 중입니다!)
-
해결됨[코드캠프] 부트캠프에서 만든 고농축 백엔드 코스
혹시 학원 진도표 같은거좀 있으면 공유해주실수 있을까요?
그런게 있으면 계획을 세우는데 도움이 될듯합니다~감사합니다~