Unit Test
Unit Test
Tests individual functions/modules. The smallest unit of testing. Jest, pytest.
Unit Test
Tests individual functions/modules. The smallest unit of testing. Jest, pytest.
A unit test is a test that independently verifies individual functions, methods, and classes, which are the smallest units of software. It began in the 1970s with Kent Beck's SUnit (Smalltalk), and today test frameworks exist for every language.
The characteristics of a good unit test are summarized by the FIRST principles: Fast (quick execution), Independent (independence between tests), Repeatable (repeating the same results), Self-Validating (automatic judgment), Timely (written at the right time). External dependencies (DB, API) are replaced with mocks to ensure test isolation.
Test structure follows the AAA pattern. Arrange (preparation: setting up test data and environment), Act (execution: calling the function under test), Assert (verification: checking whether the result matches the expected value). Each test should verify only one behavior so that the cause of a failure is easy to identify.
In practice, Jest (JavaScript), pytest (Python), JUnit (Java), Go test, and others are used. Aim for test coverage of 80% or more, while focusing on core business logic and complex conditional branches. Tests run automatically on every PR in CI to prevent regression bugs.
// Jest๋ฅผ ์ฌ์ฉํ ์ ๋ ํ
์คํธ ์์
// src/services/priceCalculator.js
export function calculateDiscount(price, userType, couponCode) {
if (price <= 0) throw new Error('Price must be positive');
let discount = 0;
// ํ์ ๋ฑ๊ธ๋ณ ํ ์ธ
if (userType === 'premium') discount += 0.1;
else if (userType === 'vip') discount += 0.2;
// ์ฟ ํฐ ํ ์ธ
if (couponCode === 'SAVE10') discount += 0.1;
else if (couponCode === 'SAVE20') discount += 0.2;
// ์ต๋ ํ ์ธ์จ ์ ํ
discount = Math.min(discount, 0.3);
return Math.round(price * (1 - discount));
}
// src/services/priceCalculator.test.js
import { calculateDiscount } from './priceCalculator';
describe('calculateDiscount', () => {
// ๊ธฐ๋ณธ ๋์ ํ
์คํธ
describe('๊ธฐ๋ณธ ํ ์ธ ๊ณ์ฐ', () => {
it('ํ ์ธ ์์ด ์๋ ๊ฐ๊ฒฉ์ ๋ฐํํ๋ค', () => {
// Arrange
const price = 10000;
// Act
const result = calculateDiscount(price, 'regular', null);
// Assert
expect(result).toBe(10000);
});
});
// ํ์ ๋ฑ๊ธ๋ณ ํ ์ธ
describe('ํ์ ๋ฑ๊ธ ํ ์ธ', () => {
it('premium ํ์์ 10% ํ ์ธ', () => {
expect(calculateDiscount(10000, 'premium', null)).toBe(9000);
});
it('vip ํ์์ 20% ํ ์ธ', () => {
expect(calculateDiscount(10000, 'vip', null)).toBe(8000);
});
});
// ์ฟ ํฐ ํ ์ธ
describe('์ฟ ํฐ ํ ์ธ', () => {
it.each([
['SAVE10', 9000],
['SAVE20', 8000],
['INVALID', 10000],
])('์ฟ ํฐ %s ์ ์ฉ ์ %d์', (coupon, expected) => {
expect(calculateDiscount(10000, 'regular', coupon)).toBe(expected);
});
});
// ๋ณตํฉ ํ ์ธ ๋ฐ ์ ํ
describe('๋ณตํฉ ํ ์ธ', () => {
it('VIP + SAVE20 = ์ต๋ 30% ํ ์ธ ์ ์ฉ', () => {
// VIP 20% + ์ฟ ํฐ 20% = 40% ์ด์ง๋ง ์ต๋ 30%๋ก ์ ํ
expect(calculateDiscount(10000, 'vip', 'SAVE20')).toBe(7000);
});
});
// ์ฃ์ง ์ผ์ด์ค
describe('์ฃ์ง ์ผ์ด์ค', () => {
it('๊ฐ๊ฒฉ์ด 0์ดํ๋ฉด ์๋ฌ', () => {
expect(() => calculateDiscount(0, 'regular', null))
.toThrow('Price must be positive');
});
it('๊ฐ๊ฒฉ์ด ์์๋ฉด ์๋ฌ', () => {
expect(() => calculateDiscount(-100, 'regular', null))
.toThrow('Price must be positive');
});
});
});
// ์ธ๋ถ ์์กด์ฑ Mocking ์์
// src/services/userService.test.js
import { getUser } from './userService';
import { db } from '../db';
// db ๋ชจ๋ ์ ์ฒด Mock
jest.mock('../db');
describe('getUser', () => {
beforeEach(() => {
jest.clearAllMocks();
});
it('์กด์ฌํ๋ ์ฌ์ฉ์๋ฅผ ๋ฐํํ๋ค', async () => {
// Mock ์ค์
db.users.findById.mockResolvedValue({
id: 1,
name: 'John'
});
const user = await getUser(1);
expect(user.name).toBe('John');
expect(db.users.findById).toHaveBeenCalledWith(1);
});
it('์กด์ฌํ์ง ์๋ ์ฌ์ฉ์๋ null ๋ฐํ', async () => {
db.users.findById.mockResolvedValue(null);
const user = await getUser(999);
expect(user).toBeNull();
});
});
Senior: "I changed the payment logic and all the existing unit tests broke. The tests depend too heavily on implementation details."
Junior: "I think that's because they even verify the order of internal method calls. Should I refactor them to verify only input and output?"
Senior: "Yes, if you write them like black-box tests, they won't break even when you refactor."
Interviewer: "What do you consider important when writing tests?"
Candidate: "Tests should verify behavior, not implementation. Tests must not break even if the internal implementation changes. Also, you should be able to tell what is being verified just from the test name, and to let the cause be identified immediately on failure, each test verifies only one behavior."
Take a mock interview on this topic โ WIA SOOM AI Interview ยท Start for free
Reviewer: "This function has 4 conditional branches, but only 1 test. Please add edge case tests."
Developer: "I'll add cases for null input, an empty array, and boundary values. Using it.each to make parameterized tests would be clean."