# 단위 테스트 생성

Copilot Chat 는 함수에 대한 단위 테스트를 생성하는 데 도움이 될 수 있습니다.

좋은 단위 테스트 제품군은 모든 프로젝트의 성공에 매우 중요합니다. 그러나 이러한 테스트를 작성하는 것은 시간이 오래 걸릴 수 있으며 종종 소홀히 하게 됩니다.
Copilot Chat 는 이러한 테스트를 생성하는 데 도움이 될 수 있습니다.

## 예제 시나리오

데이터베이스를 업데이트하기 전에 데이터의 유효성을 검사하는 Python 함수가 있다고 상상해 보세요. 유효성 검사가 예상대로 수행되도록 단위 테스트를 만들어야 합니다. 이러한 테스트를 생성하도록 요청할 Copilot Chat 수 있습니다.

```python id=validate-price
def validate_price(price: float):
  if price <= 0:
    raise ValueError("Price must be greater than 0")
  if price > 1000:
    raise ValueError("Price must be less than or equal to 1000")
```

## 예제 프롬프트

```copilot copy prompt ref=validate-price
/tests Generate unit tests for this function. Validate both success and failure, and include edge cases.
```

## 응답 예제

> \[!NOTE] 다음 응답이 예제입니다. Copilot Chat 응답은 비결정적이므로 여기에 표시된 응답과 다른 응답을 얻을 수 있습니다.

처음으로 단위 테스트를 생성하도록 요청하는 Copilot Chat 경우 프로젝트에 대한 단위 테스트를 구성할지 묻는 메시지가 표시 될 수 있습니다. 이 예제에서는 이 제안을 거절하는 것으로 가정합니다.

Copilot 는 테스트를 생성하기 위한 전략을 제공한 다음 테스트 자체를 제공합니다.

```python
import unittest
from generate_unit_tests import validate_price

class TestValidateProduct(unittest.TestCase):
  def test_price_zero(self):
    with self.assertRaises(ValueError) as context:
      validate_price(0)
    self.assertEqual(str(context.exception), "Price must be greater than 0")

  def test_price_negative(self):
    with self.assertRaises(ValueError) as context:
      validate_price(-10)
    self.assertEqual(str(context.exception), "Price must be greater than 0")

  def test_price_above_limit(self):
    with self.assertRaises(ValueError) as context:
      validate_price(1500)
    self.assertEqual(str(context.exception), "Price must be less than or equal to 1000")

  def test_price_edge_case_zero(self):
    with self.assertRaises(ValueError) as context:
      validate_price(0)
    self.assertEqual(str(context.exception), "Price must be greater than 0")

  def test_price_edge_case_max(self):
    try:
      validate_price(1000)
    except ValueError:
      self.fail("validate_price() raised ValueError unexpectedly!")

if __name__ == '__main__':
  unittest.main()
```

## 추가 읽기

* [GitHub Copilot 채팅에 대한 프롬프트 엔지니어링](/ko/copilot/concepts/prompting/prompt-engineering)
* [GitHub 부필로트 사용에 대한 모범 사례](/ko/copilot/get-started/best-practices)