(4) 1부 화폐예제 - 7,8장 객체 만들기

2021. 3. 30. 13:57개발공부/테스트 주도 개발

728x90

Github 코드보기

7장 사과와 오렌지(같지 않은 둘)


동치성 테스트는 클래스 객체 비교를 통해 같지 않은 지까지 확인해야 합니다.

 - getclass() 를 사용했습니다.

1
2
3
4
5
    public boolean equals(Object object) {
        Money money = (Money) object;
        return amount == money.amount
                && getClass().equals(money.getClass());
    }
cs



equals() 동치성 비교가 객체 인스턴스 파라미터에 다른 값을 넣어도 같다고 떴습니다.

 - Dollar, Franc 클래스 필드를 없애고 Money것을 사용하게 했습니다.

 - Dollar, Franc 클래스 생성자를 작성해줬습니다.


8장 객체 만들기


하위 클래스에 대한 직접적인 참조를 줄여 times() 구현코드를 부모 클래스 Money의 객체를 반환해주는 것으로 변경해줍니다.

 

Money에 Dollar를 반환하는 팩토리 메서드(Factory Method)를 도입할 수 있습니다.

 - Factory Method : Factory Method is a creational design pattern that provides an interface for creating objects in a superclass, but allows subclasses to alter the type of objects that will be created.

추상클래스는 비슷한 성질의 클래스들을 상속 클래스에서 관리하기 위해 사용합니다. 하위 클래스는 추상클래스 메서드를 오버라이딩 해야합니다. 그리고 Factory Method도 사용할 수 있습니다. 특징은 부모 클래스는 객체 생성을 못하고 오직 하위 클래스들만 가능하단 점입니다.

이로써 하위 클래스의 존재를 테스트에서 분리(decoupling)하고 어떤 모델 코드에도 영향을 주지 않고 상속 구조를 마음대로 변경할 수 있게 되었습니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
abstract class Money {
 
    protected int amount;
 
    public Money () {
 
    }
 
    public Money(int amount) {
        this.amount = amount;
    }
 
    static Money dollar(int amount) {
        return new Dollar(amount);
    }
 
    static Money franc(int amount) {
        return new Franc(amount);
    }
 
    abstract Money times(int multiplier);
 
}
cs

 

동치성(Equality) 테스트 코드

1
2
3
4
5
6
7
8
    @Test
    public void testEquality() {
        Money dollar1 = new Dollar(5);
        Money dollar2 = new Dollar(5);
        Money franc1 = new Franc(5);
        Money franc2 = new Franc(5);
        assertTrue(franc1.equals(franc2));
    }
cs

 


 

출처 : 테스트 주도 개발 - 켄트 벡