KPT 회고

220907 Matcher, Pattern클래스, Junit 작동방식, static block, 테스트 케이스에서 @Transactional 자동 롤백 과정

TLdkt 2022. 9. 7. 23:02
728x90
반응형

🚩Java에서 regex 쓰기: Matcher, Pattern 

//testStr 특정문자개수세기
        String regEx = "[A-Z]+";
        Pattern pattern = Pattern.compile(regEx);
        Matcher matcher = pattern.matcher(testStr);
        while (matcher.find()) {
            실제대문자개수 +=matcher.group(0).length();
        }

💚Pattern 클래스의 compile()

- compile()메서드를 통해 regex를 Pattern의 인스턴스로 생성

- matcher() 메서드로 Matcher타입의 객체 생성

[원문]

A regular expression, specified as a string, must first be compiled into an instance of this class.

The resulting pattern can then be used to create a Matcher object that can match arbitrary character sequences against the regular expression.

All of the state involved in performing a match resides in the matcher, so many matchers can share the same pattern.

https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html

 

Pattern (Java Platform SE 8 )

Enables canonical equivalence. When this flag is specified then two characters will be considered to match if, and only if, their full canonical decompositions match. The expression "a\u030A", for example, will match the string "\u00E5" when this flag is s

docs.oracle.com

💚Matcher 클래스의 find(), group()

-find()가 true인 동안 

-받아온 pattern에 맞는 결과 String 리턴

-해당 Sting의 길이 구하기

 

https://docs.oracle.com/javase/7/docs/api/java/util/regex/Matcher.html

 

Matcher (Java Platform SE 7 )

Returns the input subsequence captured by the given named-capturing group during the previous match operation. If the match was successful but the group specified failed to match any part of the input sequence, then null is returned. Note that some groups,

docs.oracle.com

 


👀JUnit 작동방식 

-@Test 인식하면

-테스트 클래스의 객체 생성하고

-테스트 메서드 하나마다 쓰고 버리고 반복

참고)

템플릿 패턴에서 쓰던 훅 메서드

@BeforeEach에서 객체 생성하려면 클래스 내 필드로 먼저 선언한다

 

https://goodgid.github.io/How-JUnit-Works/

 

JUnit의 동작 방식

Index

goodgid.github.io

🌱static block

import java.util.HashMap;
import java.util.Map;

public class CryptoCurrency {
    public static Map<String, String> map = new HashMap<>();

    static {
        map.put("BTC", "Bitcoin");
        map.put("ETH", "Ethereum");
        map.put("ADA", "ADA");
        map.put("POT", "Polkadot");
    }
}

 

-클래스 변수를 초기화시키는 용도

-클래스 변수 로드되면 바로 실행된다

-생성자 전에 실행될 수 있다 

// Java Program to Illustrate Execution of Static Block
// Before Constructors

// Class 1
// Helper class
class Test {

	// Case 1: Static variable
	static int i;
	// Case 2: Non-static variable
	int j;

	// Case 3: Static blocks
	static
	{
		i = 10;
		System.out.println("static block called ");
	}

	// Constructor calling
	Test() { System.out.println("Constructor called"); }
}

// Class 2
// Main class
class GFG {

	// Main driver method
	public static void main(String args[])
	{

		// Although we have two objects, static block is
		// executed only once.
		Test t1 = new Test();
		Test t2 = new Test();
	}
}

 

실행 절차

  1. 클래스가 로딩된다.
  2. 클래스 변수가 있으면 메모리를 생성한다..
  3. static 블록이 선언된 순서대로 실행된다.
  • 참고 : 클래스 로딩 절차
  1. JRE 라이브러리 폴더에서 클래스를 찾는다.
  2. 없으면, CLASSPATH 환경 변수에 지정된 폴더에서 클래스를 찾는다.
  3. 찾았으면, 그 클래스 파일이 올바른 바이트코드인지 검증한다.
  4. 올바른 바이트코드라면, Method Area 영역으로 파일을 로딩한다.
  5. 클래스 블록이 있으면 순서대로 그 블록을 실행한다.
  6. 클래스 안에 static block (스태틱 블록)들이 있으면 순서대로 그 블록을 실행한다.

출처: https://uoonleen.tistory.com/6

https://www.geeksforgeeks.org/static-blocks-in-java/

 

Static Blocks in Java - GeeksforGeeks

A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.

www.geeksforgeeks.org

 

 

⚓Test에서 @Transactional 자동 롤백 기능

스프링에서 테스트를 실행하면 TransactionalTestExecutionalListner가 자동으로 구성되는데,

얘가 test-managed transaction 실행할 때 테스트 클래스의 @Transactional이나 @Test 애너테이션을 인식한다.

이 리스너가 자동으로 롤백되는 트랜잭션을 만들어준다.

기본 상태가 롤백이므로 이 상태를 변경하려면 추가 조작이 필요하다

데이터베이스에 연결되는 트랜잭션(test-managed transaction only)만 롤백되니 주의 ! 

[원문]

더보기

What Does @Transactional Do?

Running tests while starting up the Spring application context, a TransactionalTestExecutionListener is automatically configured. This listener provides support for executing tests with test-managed transactions. It notices the @Transactional on the test class or individual @Test methods and creates a new transaction that is then automatically rolled back after test completion. The default is rollback. This behavior can be changed, however, by putting @Commit or @Rollback at the class or method level. If you need more control over your transactions, you can use the static methods in TestTransaction. They allow you to start and end transactions, flag them for commit or rollback or check the transaction status.

Beware: Only Test-Managed Transactions Are Rolled Back

Transactions are not rolled back when the code that is invoked does not interact with the database. An example would be writing an end-to-end test that uses RestTemplate to make an HTTP request to some endpoint that then makes a modification in the database. Since the RestTemplate does not interact with the database (it just creates and sends an HTTP request), @Transactional will not rollback anything that is an effect of that HTTP request. This is because a separate transaction, one not controlled by the test, will be started.

https://relentlesscoding.com/posts/automatic-rollback-of-transactions-in-spring-tests/

 

Automatic Rollback of Transactions in Spring Tests

Put @Transactional on your test class or methods and test-managed transactions will automatically be rollbacked.

relentlesscoding.com

💻앞으로 챙겨야 할 것

stream 더 적극적으로 활용하자

test 케이스에서 @BeforeEach 등에서 객체를 생성하더라도 필드 선언은 전역으로 해줘야 한다 

아스키코드에서 대소문자 범위 정도는 외우자 

728x90
반응형