inflearn logo
강의

강의

N
챌린지

챌린지

멘토링

멘토링

N
클립

클립

로드맵

로드맵

지식공유

스프링부트 JUnit 테스트 - 시큐리티를 활용한 Bank 애플리케이션

Account Delete 테스트 버그 수정(FK 제약 조건 해제)

순수 EntityManager vs Spring Data JPA 테스트

해결된 질문

721

jeidiiy

작성한 질문수 13

0

프로젝트를 하면서 궁금한 점이 생겨 질문드립니다.

@AutoConfigureMockMvc와 @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK) 만 적용한 상태로 테스트 코드를 작성했습니다. 그리고 @Autowired를 통해 순수 EntityManager를 주입받아서 직접 영속성을 관리하는 레포지토리가 있습니다. 그런데 직접 EntityManager를 주입받은 Repository 빈은 테스트 주입 시 EntityManager가 없다는 오류가 발생합니다. 하지만 Spring Data JPA의 JpaRepository를 상속받은 인터페이스를 @Autowired로 주입받으면 이는 문제없이 테스트가 동작합니다. 혹시 어떤 차이점이 있는지 알 수 있을까요?

 

@Repository
public class UserRepository {
    @PersistenceContext
    private EntityManager em;

    public User save(final User user) {
        em.persist(user);
        return user;
    }

    public Optional<User> findByEmail(final String email) {
        List<User> users = em.createQuery("select u from User u where u.email=:email", User.class) 
                             .setParameter("email", email)
                             .getResultList();return users.isEmpty() ? Optional.empty() : Optional.of(users.get(0));
    }
}

 

public interface UserJpaRepository extends JpaRepository<User, Long> {
    public Optional<User> findByEmail(final String email);
}

 

@ActiveProfiles("test")
@AutoConfigureMockMvc
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK)
class AjaxEmailPasswordAuthenticationFilterTests extends DummyObject {

    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private MockMvc mockMvc;
    @Autowired
    private UserJpaRepository userJpaRepository;
    @Autowired
    private PasswordEncoder passwordEncoder;

    @BeforeEach
    void setup() {
    	userJpaRepository.save(User.builder()
            .email("test@gmail.com")
	    .username("test")
	    .password(passwordEncoder.encode("1234")).build());
    }

    @DisplayName("이메일 기반 회원가입 유저 로그인")
    @Nested
    class LoginByEmailTests {
    	@DisplayName("로그인 성공")
    	@Test
    	void success_test() throws Exception {
            //given
	    String url = Endpoint.Api.LOGIN_WITH_EMAIL;
	    EmailLoginUserRequestDto requestDto = EmailLoginUserRequestDto.builder()
	    .email("test@gmail.com")
	    .password("1234")
	    .build();

	    //when
	    ResultActions resultActions = mockMvc.perform(
	        post(url)
		    .contentType(MediaType.APPLICATION_JSON)
		    .content(objectMapper.writeValueAsString(requestDto))
	    );

	    //then
	    resultActions
		.andExpect(status().isOk())
		.andExpect(jsonPath("$.id").exists())
		.andExpect(jsonPath("$.redirectUrl").exists());
	}
    }
}

spring-boot junit

답변 1

1

최주호

테스트시에 메모리에 없어서 @Imoprt 해줘야 합니다

요청/응답 DTO 관련 문의

0

174

2

안녕하세요 인증이 필요한 url을 위하여 /s를 붙이는것에 대해 질문있습니다.

0

161

1

validation aop사용에 대해서 질문있습니다.

0

246

2

Dummy 클래스 위치에 대한 질문

0

294

2

테스트 방식에 관해서 질문이 있어요

0

293

2

스프링 버전업일 경우에는 Pointcut @PostMapping 조건이 달라질까요?

1

435

1

equals와 longValue 관련 질문드립니다

0

332

1

계좌번호를 Long 타입으로 하는 이유가 무엇일까요?!

0

501

2

[정보공유] Hibernate 로그 작동 안하시는 분들!!

3

346

0

UserControllerTest 테스트 실패 문의

0

319

1

스프링 시큐리티 6.2 버전 이후로 apply() 메서드를 이용한 JwtAuthenticationFilter 가 등록이 안됩니다.

2

1108

1

import 오류

0

429

3

spring initializer gradle 에서 3.x.x 대 밖에 없어요. 2.x.x는 보이지 않는데 어떡하져

0

440

2

안녕하세요 로그엔 성공적으로 들어온것같습니다..

0

237

1

JwtAuthorizationfilter test mvc.performget 관련 질문입니다!

0

288

1

JwtAuthorizationfilter test mvc.performget 부

0

229

1

longValue() 질문

0

231

1

jwt 인가필터 규현및 등록

0

334

1

스프링부트 3버전

1

336

1

권한처리를 위한 세션강제주입

0

418

1

JwtVO 를 인터페이스로 만든 이유

0

361

1

계좌 조회 질문드립니다

0

230

1

DummyObject 에 대하여

0

310

2

DTO를 이너클래스로 계속추가하는 이유

0

700

2