Skip to content

Commit

Permalink
feat(test): 상태를 갖는 싱글톤 구현
Browse files Browse the repository at this point in the history
  • Loading branch information
CODe5753 committed Apr 16, 2022
1 parent 1ae80c7 commit ea72c62
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
15 changes: 15 additions & 0 deletions src/test/java/hello/core/singleton/StatefulService.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package hello.core.singleton;

public class StatefulService {

private int price; // 상태를 유지하는 필드

public void order(String name, int price) {
System.out.println("name = " + name + " price = " + price);
this.price = price; // 여기가 문제!
}

public int getPrice() {
return price;
}
}
40 changes: 40 additions & 0 deletions src/test/java/hello/core/singleton/StatefulServiceTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package hello.core.singleton;

import org.junit.jupiter.api.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;

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

class StatefulServiceTest {

@Test
void statefulServiceSingleton() {
ApplicationContext ac = new AnnotationConfigApplicationContext(TestConfig.class);
StatefulService statefulService1 = ac.getBean(StatefulService.class);
StatefulService statefulService2 = ac.getBean(StatefulService.class);

// ThreadA: A 사용자가 1만원 주문
statefulService1.order("userA", 10000);

// ThreadB: B 사용자가 2만원 주문
statefulService1.order("userB", 20000);

// ThreadA: A 사용자가 주문 금액 조회
int price = statefulService1.getPrice();
System.out.println("price = " + price);

assertThat(statefulService1.getPrice()).isEqualTo(20000);
}

static class TestConfig {
@Bean
public StatefulService statefulService() {
return new StatefulService();
}
}


}

0 comments on commit ea72c62

Please sign in to comment.