Spring 14 (23.04.25)

Jane·2023년 4월 25일
0

IT 수업 정리

목록 보기
112/124

1. 통합 테스트 (이어서)

1-1. 메인 페이지 MockTest

HomeControllerTest.java

package edu.global.ex.controller;

import static org.junit.jupiter.api.Assertions.*;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@SpringBootTest
@AutoConfigureMockMvc
class HomeControllerTest {

	@Autowired
	private MockMvc mockMvc;

	// GetMapping(/)
	@Test
	void testHome() throws Exception {
		mockMvc.perform(MockMvcRequestBuilders.get("/")).andExpect(MockMvcResultMatchers.status().isOk());
	}

}
  • Spring Boot를 돌려 "/" 주소 확인하고, 네트워크에서 200 확인. JUnit Test 실행.

1-2. 테스트 로그 남기기

  • andDo(print()); 추가
	// GetMapping(/)
	@Test
	void testHome() throws Exception {
		mockMvc.perform(MockMvcRequestBuilders.get("/"))
		.andExpect(MockMvcResultMatchers.status().isOk())
		.andDo(print());
	}
  • 통합테스트 할 때 프린트 로그는 문서로 남겨야 한다.

MockHttpServletRequest:
HTTP Method = GET
Request URI = /
Parameters = {}
Headers = []
Body = null
Session Attrs = {}


Handler:
Type = edu.global.ex.controller.HomeController
Method = edu.global.ex.controller.HomeController#home()


Async:
Async started = false
Async result = null


Resolved Exception:
Type = null


ModelAndView:
View name = home
View = null
Model = null


FlashMap:
Attributes = null


MockHttpServletResponse:
Status = 200
Error message = null
Headers = [Content-Language:"en", X-Content-Type-Options:"nosniff", X-XSS-Protection:"1; mode=block", Cache-Control:"no-cache, no-store, max-age=0, must-revalidate", Pragma:"no-cache", Expires:"0", X-Frame-Options:"DENY"]
Content type = null
Body =
Forwarded URL = /WEB-INF/views/home.jsp
Redirected URL = null
Cookies = []

1-3. userHome MockTest

  • 유저 홈에 접속하면 권한이 걸려 있어서 로그인해야한다.
	// GetMapping(/user/userHome)
	@Test
	void testUserHome() throws Exception {
		mockMvc.perform(MockMvcRequestBuilders.get("/user/userHome"))
		.andExpect(MockMvcResultMatchers.status().isOk())
		.andDo(print());
	}
  • 테스트를 실행하면 Spring Security 권한에 걸려서 실패.

MockHttpServletRequest:
HTTP Method = GET
Request URI = /user/userHome
Parameters = {}
Headers = []
Body = null
Session Attrs = {SPRING_SECURITY_SAVED_REQUEST=DefaultSavedRequest [http://localhost/user/userHome]}


Handler:
Type = null


Async:
Async started = false
Async result = null


Resolved Exception:
Type = null


ModelAndView:
View name = null
View = null
Model = null


FlashMap:
Attributes = null


MockHttpServletResponse:
Status = 302
Error message = null
Headers = [X-Content-Type-Options:"nosniff", X-XSS-Protection:"1; mode=block", Cache-Control:"no-cache, no-store, max-age=0, must-revalidate", Pragma:"no-cache", Expires:"0", X-Frame-Options:"DENY", Location:"http://localhost/login"]
Content type = null
Body =
Forwarded URL = null
Redirected URL = http://localhost/login
Cookies = []

  • 권한에 걸려서 "localhost/login"으로 리다이렉트 할 수 있도록 동작하게 된다.
  • @WithMockUser 설정을 추가한다.
	// GetMapping(/user/userHome)
	@Test
	@WithMockUser(username = "user", password = "user", roles = "USER")
	void testUserHome() throws Exception {
		mockMvc.perform(MockMvcRequestBuilders.get("/user/userHome")).andExpect(MockMvcResultMatchers.status().isOk())
				.andDo(print());
	}

MockHttpServletRequest:
HTTP Method = GET
Request URI = /user/userHome
Parameters = {}
Headers = []
Body = null
Session Attrs = {SPRING_SECURITY_CONTEXT=SecurityContextImpl [Authentication=UsernamePasswordAuthenticationToken [Principal=org.springframework.security.core.userdetails.User [Username=user, Password=[PROTECTED], Enabled=true, AccountNonExpired=true, credentialsNonExpired=true, AccountNonLocked=true, Granted Authorities=[ROLE_USER]], Credentials=[PROTECTED], Authenticated=true, Details=null, Granted Authorities=[ROLE_USER]]]}


Handler:
Type = edu.global.ex.controller.HomeController
Method = edu.global.ex.controller.HomeController#user_home()


Async:
Async started = false
Async result = null


Resolved Exception:
Type = null


ModelAndView:
View name = user/userHome
View = null
Model = null


FlashMap:
Attributes = null


MockHttpServletResponse:
Status = 200
Error message = null
Headers = [Content-Language:"en", X-Content-Type-Options:"nosniff", X-XSS-Protection:"1; mode=block", Cache-Control:"no-cache, no-store, max-age=0, must-revalidate", Pragma:"no-cache", Expires:"0", X-Frame-Options:"DENY"]
Content type = null
Body =
Forwarded URL = /WEB-INF/views/user/userHome.jsp
Redirected URL = null
Cookies = []

  • 테스트에 통과되어 user/userHome을 포워딩한다.
  • user, user로 접속하여(가상계정) 유저 권한이 부여된 상태로 보여지게 된다.
    (UserDetailsVO에 있는 내용들을 사용한다.)

1-4. adminHome Test

// GetMapping(/admin/adminHome)
	@Test
	@WithMockUser(username = "admin", password = "admin", roles = "ADMIN")
	void testAdminHome() throws Exception {
		mockMvc.perform(MockMvcRequestBuilders.get("/admin/adminHome")).andExpect(MockMvcResultMatchers.status().isOk())
				.andDo(print());
	}

MockHttpServletRequest:
HTTP Method = GET
Request URI = /admin/adminHome
Parameters = {}
Headers = []
Body = null
Session Attrs = {SPRING_SECURITY_CONTEXT=SecurityContextImpl [Authentication=UsernamePasswordAuthenticationToken [Principal=org.springframework.security.core.userdetails.User [Username=admin, Password=[PROTECTED], Enabled=true, AccountNonExpired=true, credentialsNonExpired=true, AccountNonLocked=true, Granted Authorities=[ROLE_ADMIN]], Credentials=[PROTECTED], Authenticated=true, Details=null, Granted Authorities=[ROLE_ADMIN]]]}


Handler:
Type = edu.global.ex.controller.HomeController
Method = edu.global.ex.controller.HomeController#admin_home()


Async:
Async started = false
Async result = null


Resolved Exception:
Type = null


ModelAndView:
View name = admin/adminHome
View = null
Model = null


FlashMap:
Attributes = null


MockHttpServletResponse:
Status = 200
Error message = null
Headers = [Content-Language:"en", X-Content-Type-Options:"nosniff", X-XSS-Protection:"1; mode=block", Cache-Control:"no-cache, no-store, max-age=0, must-revalidate", Pragma:"no-cache", Expires:"0", X-Frame-Options:"DENY"]
Content type = null
Body =
Forwarded URL = /WEB-INF/views/admin/adminHome.jsp
Redirected URL = null
Cookies = []

2. 기타 테스트

  • 시스템 테스트 / 부하 테스트
    • 1000 명을 동시 접속시키게 한다면?
    • 툴을 이용하여 어떤 상황이 발생하는지 체크해본다
  • 인수 테스트

나머지 내용들은 조금 더 진행한 이후에 진행 예정


2-1. DataSource Connection 테스트

package edu.global.ex.db;

import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.*;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

import javax.sql.DataSource;

import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit.jupiter.SpringExtension;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@SpringBootTest
class DataSourceTest {

	@Autowired
	private DataSource datasource;

	@Disabled
	@Test
	void testDataSource() {
		System.out.println(datasource);
		assertNotNull(datasource);
	}

	@Test
	void testConnetion() throws Exception {
		System.out.println("DS : " + datasource);

		try (Connection conn = datasource.getConnection()) {
			System.out.println("Connection : " + conn);

			assertThat(conn).isInstanceOf(Connection.class);
			assertEquals(100, getLong(conn, "select 100 from dual"));
			// assertTrue(0 < getLong(conn, "select count(*) from User"));

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private long getLong(Connection conn, String sql) {
		long result = 0;
		try (Statement stmt = conn.createStatement()) {
			ResultSet rs = stmt.executeQuery(sql);
			if (rs.next()) {
				result = rs.getLong(1);
			}
			rs.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return result;
	}

}
profile
velog, GitHub, Notion 등에 작업물을 정리하고 있습니다.

0개의 댓글