본문 바로가기

카테고리 없음

인터페이스분리원칙, 가짜 의존성 주입, 단위테스트

https://ko.wikipedia.org/wiki/%EC%9D%B8%ED%84%B0%ED%8E%98%EC%9D%B4%EC%8A%A4_%EB%B6%84%EB%A6%AC_%EC%9B%90%EC%B9%99

 

인터페이스 분리 원칙 - 위키백과, 우리 모두의 백과사전

위키백과, 우리 모두의 백과사전. 인터페이스 분리 원칙은 클라이언트가 자신이 이용하지 않는 메서드에 의존하지 않아야 한다는 원칙이다.[1] 인터페이스 분리 원칙은 큰 덩어리의 인터페이스

ko.wikipedia.org

 

 

1. 인터페이스 분리원칙에 의해 url 연결 성공, 실패 메서드를 분리한다 

Web.js

 

// 성공
const processFetchContent = (text) => {
    const included = text.includes("<p>메리크리스마스</p>")
    if(included){
        return {success: true, status: "ok"}
    }
    return {success: false, status: "Missing text"}
}

// 실패 
const processFetchError = (err) => {
    return {success: false, status: err}
}

module.exports = {Web}

 

 

1-1. 테스트할 url은 로컬호스트 3000, try-catch로직에 url 성공, 실패 메서드를 주입시킨다.

 

const Web = async () => {
    try{
        const result = await adapter.fetchUrlText("http://localhost:3000/")
        if(!result.ok){
            throw result.text
        }
        const text = result.text
        return processFetchContent(text)
    }
    catch (err){
        throw processFetchError(err)
    }
}

 

 

2. 가짜의존성주입을 위해 반환값은  mockReturnValue로 대체될 것이다.

network.js

 

const fetchUrlText = async (url) => {
    const resp = await fetch(url);
    if(resp.ok){
        const text = await resp.text();
        return {ok:true, text}
    }
    return {ok:false, text:resp.statusText}
}
module.exports = {
    fetchUrlText
}

 

 

3. 테스트 코드실행 - 성공 

 

jest.mock("../network")
const stub = require("../network")
const webverifier = require("../web")

describe("web", () => {
    beforeEach(jest.resetAllMocks)
    

    // mocking을 이용한 가짜 의존성 주입
    test("web content", async () => {
        stub.fetchUrlText.mockReturnValue({
            ok:true,
            text: "<p>메리크리스마스</p>>"
        })
        // localhost:3000 성공,실패  테스트
        const result = await webverifier.Web()
        expect(result.success).toBe(true)
        expect(result.status).toBe("ok")
    })

	// mocking을 이용한 가짜 의존성 주입
     test("web content2", async () => {
        stub.fetchUrlText.mockReturnValue({
            ok:true,
            text: "<p>한가위</p>>"
        })
         // localhost:3000 성공,실패  테스트
        const result = await webverifier.Web()
        expect(result.success).toBe(false)
        expect(result.status).toBe("Missing text")
    })

})

 

 

 

 

 

참고한 책입니다 

https://www.yes24.com/Product/Goods/140076332

 

단위 테스트의 기술 - 예스24

기본 개념과 실전 예제, 리팩터링, 유지 보수성 향상, 조직 내 테스트 도입까지한 권으로 끝내는 단위 테스트 완벽 가이드이 책의 최종 목표는 더 견고한 코드를 작성하고 싶은 모든 개발자가 단

www.yes24.com