구글의 제안 : 70% unit tests, 20% integratoin tests, 10% end-to-end tests
public testGetPageHierarchyAsxml() throws Exception {
givenPages("PageOne", "PageOne.ChildOne", "PageTwo");
whenRequestIsIssued("root", "type:pages");
thenResponseShouldBeXML();
}
public void testGetPageHierarchyHasRightTags() throws Exception {
givenPages("PageOne", "PageOne.ChildOne", "PageTwo");
whenRequestIsIssued("root", "type:pages");
thenResponseShouldContain("<name>PageOne</name>", "<name>ChildOne</name>", "<name>PageTwo</name>");
}
@RestController
public class ExampleController {
private final PersonRepository personRepo;
@Autowired
public ExampleController(final PersonRepository personRepo) {
this.personRepo = personRepo;
}
@GetMapping("/hello/{lastName}")
public String hello(@PathVariable final String lastName) {
Optional<Person> foundPerson = personRepo.findByLastName(lastName);
return foundPerson
.map(person -> String.format("Hello %s %s!",
person.getFirstName(),
person.getLastName()))
.orElse(String.format("Cannot hello to unknown")); // 이부분 테스트
}
}
public class ExampleControllerTest {
// 테스트 대상
private ExampleController subject;
@Mock
private PersonRepository personRepo;
@Before
public void setUp() throws Exception {
initMocks(this);
subject = new ExampleController(personRepo);
}
@Test
public void shouldReturnFullNameOfAPerson() throws Exception {
// given
Person peter = new Person("Peter", "Pan");
given(personRepo.findByLastName("Pan"))
.willReturn(Optional.of(peter));
// when
String greeting = subject.hello("Pan");
// then
assertThat(greeting, is("Hello Peter Pan!"));
}
@Test
public void shouldTellIfPersonIsUnknown() throws Exception {
// given
given(personRepo.findByLastName(anyString()))
.willReturn(Optional.empty());
// when
String greeting = subject.hello("Pan");
// then
assertThat(greeting, is("Cannot hello to unknown"));
}
}
@RunWith(SpringRunner.class)
@DataJpaTest
public class PersonRepositoryIntegrationTest {
@Autowired
private PersonRepository subject;
@After
public void tearDown() throws Exception {
subject.deleteAll();
}
@Test
public void shouldSaveAndFetchPerson() throws Exception {
// given
Person peter = new Person("Peter", "Pan");
subject.save(peter);
// when
Optional<Person> maybePeter = subject.findByLastName("Pan");
// then
assertThat(maybePeter, is(Optional.of(peter)));
}
}
@RunWith(SpringRunner.class)
@SpringBootTest
public class WeatherClientIntegrationTest {
@Autowired
private WeatherClient subject;
@Rule
public WireMockRule wireMockRule = new WireMockRule(8089); // mock 서버를 띄운다.
@Test
public void shouldCallWeatherService() throws Exception {
// given : mock 서버에 응답을 설정한다.
wireMockRule.stubFor(get(urlPathEqualTo("/some-test-api-key/53.5511,9.9937"))
.willReturn(aResponse()
.withBody(FileLoader.read("classpath:weatherApiResponse.json"))
.withHeader(CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.withStatus(200)));
// when : weatherClient가 mock 서버로부터 응답을 받는다.
Optional<WeatherResponse> weatherResponse = subject.fetchWeather();
// then : 받아온 응답이 기대값과 일치하는 지 확인한다.
Optional<WeatherResponse> expectedResponse = Optional.of(new WeatherResponse("Rain"));
assertThat(weatherResponse, is(expectedResponse));
}
}
package com.example.project;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
class CalculatorTests {
@Test
@DisplayName("1 + 1 = 2")
void addsTwoNumbers() {
Calculator calculator = new Calculator();
assertEquals(2, calculator.add(1, 1), "1 + 1 should equal 2");
}
@ParameterizedTest(name = "{0} + {1} = {2}")
@CsvSource({
"0, 1, 1",
"1, 2, 3",
"49, 51, 100",
"1, 100, 101"
})
void add(int first, int second, int expectedResult) {
Calculator calculator = new Calculator();
assertEquals(expectedResult, calculator.add(first, second),
() -> first + " + " + second + " should equal " + expectedResult);
}
}
public class BrokeragePolicyTest {
PurchaseBrokeragePolicy purchaseBrokeragePolicy;
RentBrokeragePolicy rentBrokeragePolicy;
@BeforeEach
public void setup() {
purchaseBrokeragePolicy = new PurchaseBrokeragePolicy();
rentBrokeragePolicy = new RentBrokeragePolicy();
}
@Test
public void testPurchaseBrokeragePolicy() {
// given
Long price = 30_000_000L;
// when
Long result = purchaseBrokeragePolicy.calculate(price);
// then
Assertions.assertEquals(result, 100_000L);
Assertions.assertEquals(
purchaseBrokeragePolicy.calculate(100_000_000L), 500_000L);
Assertions.assertEquals(
purchaseBrokeragePolicy.calculate(500_000_000L), 2_000_000L);
Assertions.assertEquals(
purchaseBrokeragePolicy.calculate(800_000_000L), 4_000_000L);
Assertions.assertEquals(
purchaseBrokeragePolicy.calculate(1_000_000_000L), 9_000_000L);
}
@Test
public void testRentBrokeragePolicy() {
Assertions.assertEquals(
rentBrokeragePolicy.calculate(30_000_000L), 150_000L);
Assertions.assertEquals(
rentBrokeragePolicy.calculate(100_000_000L), 500_000L);
Assertions.assertEquals(
rentBrokeragePolicy.calculate(500_000_000L), 2_000_000L);
Assertions.assertEquals(
rentBrokeragePolicy.calculate(800_000_000L), 6_400_000L);
Assertions.assertEquals(
rentBrokeragePolicy.calculate(1_000_000_000L), 8_000_000L);
}
}