(Udacity) Lesson 6: TESTING

치즈말랑이·2021년 10월 13일
0

As a user, I can in order to .

1. 다음 중 테스트할 수 있는 것은?

1) As a user, I can click on the "tacos" tab to view a list of tacos that are available.
2) As a user, I can click on the "order taco" button next to a taco on the tacos tab to add it to my order.
3) As a user, I can click on the "schedule delivery" button while viewing an order to see a modal window with a time picker and an address field.
4) As a user, I can click on the "schedule" button of the schedule delivery modal to save the time and address selected in the window.

2. "As a user, I can click on the "schedule" button of the schedule delivery modal to save the time and address selected in the window." 는 Unit Test와 Integration Test중에 뭘 해야 하는가?

답: Integration Test
Unit test는 함수 하나하나 테스트하는것이기 때문에.

3. "As a user, I can click on the "schedule" button of the schedule delivery modal to save the time and address selected in the window." 에서 변화를 테스트 하기 위해 필요한 환경 조건은?

1) Browser
2) Platform Runtime(JDK)
3) Application Files
4) Database

Browser로 확인, Database에 정보 저장

4. 다음 중 TDD(Test-Driven Development) 작동을 위한 순서는?

1) 테스트를 먼저 생성한 다음 요구 사항을 기준으로 코드를 작성한다.
2) 코드를 먼저 작성하고 요구사항이 생성된다. 요구 사항을 검증하기 위해 유닛 테스트가 작성된다.
3) 요구사항이 먼저 생성되고 코드가 작성된다. 유닛테스트는 요구사항에 맞는 코드를 검증하기 위해 사용된다.
4) 요구사항이 먼저 생성되고 이것을 검증하기 위해 유닛테스트가 작성된다. 유닛테스트가 통과되면 코드가 쓰여진다.

설계 -> 테스트 (테스트 코드 작성) -> 개발 (real 코드 작성)

5. 유효한 assertions는?

1) assertTrue
2) assertNotNull
3) assertNotEquals
4) assertArrayEquals

5) assertArrayEmpty

6. 테스트에 맞는 알고리즘을 완성해라

class Course1ApplicationTests {

	@Test
	void testFizzBuzz(){
		FizzBuzzService fbs = new FizzBuzzService();

		// check non-divisible numbers return themselves
		assertEquals("1", fbs.fizzBuzz(1));
		assertEquals("47", fbs.fizzBuzz(47));
		assertEquals("121", fbs.fizzBuzz(121));

		// check numbers divisible by 3
		assertEquals("Fizz", fbs.fizzBuzz(3));
		assertEquals("Fizz", fbs.fizzBuzz(333));

		//check numbers divisible by 5
		assertEquals("Buzz", fbs.fizzBuzz(5));
		assertEquals("Buzz", fbs.fizzBuzz(85));

		//check numbers divisible by 3 and 5
		assertEquals("FizzBuzz", fbs.fizzBuzz(15));
		assertEquals("FizzBuzz", fbs.fizzBuzz(75));

		//check invalid inputs
		assertThrows(IllegalArgumentException.class, () -> fbs.fizzBuzz(0));
		assertThrows(IllegalArgumentException.class, () -> fbs.fizzBuzz(-1));
	}
}
    public String fizzBuzz(int number) {
        if (number == 0 || number == -1) {
            throw new IllegalArgumentException("Value must be greater than 0");
        } else if (number == 15 || number == 75) {
            return "FizzBuzz";
        } else if (number % 3 == 0) {
            return "Fizz";
        } else if (number % 5 == 0) {
            return "Buzz";
        } else {
            return "" + number;
        }
    }

7. 유닛 테스트를 할 때 IDE가 제공하는 장점은?

1) Code Coverage
2) Debugging

3) Speed
4) Unit Test Reports

8. DeliveryService class와 DeliveryServiceTest에서 어떤 내용이 유닛테스트에서 테스트되겠는가?

1)

throw new illegalArgumentException(
	"Cannot schedule a delivery in the past"
};

2)

throw new illegalArgumentException(
	"Cannot schedule a delivery for 0 tacos. Why would you do that??"
};

3)

System.out.println("Scheduling a Delivery");

4)

return deliveryMapper.findDelivery(deliveryId);

5)

return deliveryMapper.findTacosForDelivery(deliveryId);

9. Thymeleaf로 작성된 HTML을 보고, 이 페이지가 실행되었을때 셀레니움 스크립트가 뭘 할건지 고르시오

home.html

</head>
   <body>
       <form action="#" th:action="@{'/simplehome'}" method="POST">
           <input id=”submit” type="submit" value="Visit me">
       </form>
       <h1 th:if="${firstVisit}">Hello, homepage!</h1>
       <h1 th:unless="${firstVisit}">Welcome back!</h1>
   </body>
</html>

SeleniumExample.java

public static void main(String[] args) throws InterruptedException {
   WebDriverManager.chromedriver().setup();
   WebDriver driver = new ChromeDriver();
   driver.get("http://localhost:8080/simplehome");
   driver.findElement(By.id(“submit”)).click();
   Thread.sleep(5000);
   driver.quit();
}

답: Open http://localhost:8080/simplehome in a new Chrome browser, find the button with the id “submit” and click it.

10. id가 없을때 input 요소를 참조할 수 있는것은?

<form class=”simpleForm” action="#" th:action="@{'/simplehome'}" method="POST">
   <input class=”submitButton” name=”submit” type="submit" value="Visit me">
</form>

1) driver.findElement(By.name("submit")).click();
2) driver.findElement(By.className("submitButton")).click();
3) driver.findElement(By.tagName("input")).click();
4) driver.findElement(By.cssSelector("input.submitButton")).click();
5) driver.findElement(By.xpath("//input[@value='Visit me']")).click();

11. Selenium 스크립트에서 http://localhost:8080/animal로 페이지를 연 다음, 각 필드에 대한 값을 입력하고 제출 버튼을 누른다. 이것을 5회 제출하는 문서를 작성하시오.

/l5e3/src/test/java/com/example/demo/SeleniumTest.java

package com.example.demo;

import io.github.bonigarcia.wdm.WebDriverManager;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.springframework.boot.test.context.SpringBootTest;


import java.util.List;
@SpringBootTest
public class SeleniumTest {
    @Test
    public static void main(String[] args) throws InterruptedException {
        //start the driver, open chrome to our target url
        WebDriverManager.chromedriver().setup();
        WebDriver driver = new ChromeDriver();
        driver.get("http://localhost:8080/animal");


        //find the fields we want by id and fill them in
        WebElement inputField = driver.findElement(By.id("animalText"));
        inputField.sendKeys("Manatee");

        inputField = driver.findElement(By.id("adjective"));
        inputField.sendKeys("Whirling");

        List<WebElement> trainingResults = driver.findElements(By.className("trainingMessage"));

        // The field-values don’t clear on submit for our simple app, so just submit it 5 times
        // However, the elements gets removed from the DOM structure after each submit.
        for(int i = 0; i < 5; i++) {
            // We are re-assigning the inputField because this element gets removed from the DOM structure after each iteration.
            // Otherwise, you'll get org.openqa.selenium.StaleElementReferenceException at runtime.
            inputField = driver.findElement(By.id("adjective"));
            inputField.submit();

            System.out.println("trainingResults.size() = " + trainingResults.size());
        }

        // then get the element by the class conclusionMessage and print it
        WebElement conclusionResult = driver.findElement(By.className("conclusionMessage"));
        System.out.println("conclusionResult.getText() = " + conclusionResult.getText());

        Thread.sleep(5000);
        driver.quit();
    }
}

12. JUnit과 셀레니움을 매칭하시오

JUnit ----------- 셀레니움
1) @BeforeAll - WebDriverManager.chromedriver().setup();
2) @BeforeEach - driver.get("http://my-webpage.biz/fizzBuzz");
3) @Test - driver.findElement(By.id("bazz"));
4) @AfterAll - driver.quit();

13. 5번 제출되었을 때 메세지를 바꾸고 싶다. 어떤 JUnit과 셀레니움의 요소가 이 테스트를 도와줄 수 있는가?

1) 셀레니움 페이지 오브젝트 모델
2) JUnit Assertions
3) 셀레니움 WebDriver.get

4) 셀레니움 By.cssSelector
5) JUnit @AfterEach

13. Selenium을 사용하여 페이지를 로드하는 데 시간이 걸릴 경우 페이지에 아직 존재하지 않을 수 있는 요소를 검색하기 전에 드라이버가 대기해야 하는가?

답: 그렇다. 요소를 찾지 못하면 드라이버가 예외 처리를 해야된다. null을 return하지는 않는다. 셀레니움이 보고 있는 페이지는 사용자가 보고 있는 페이지와 같아야 한다.

14. 셀레니움 테스트를 시작하기 전에 페이지가 로드될때까지 기다리는 가장 좋은 방법은?

1) 페이지가 충분히 로드될 시간을 가질 수 있게 Thread.sleep()을 추가한다.
2) WebDriverWait 개체를 사용하여 웹드라이버가 페이지에서 특정 요소를 찾을 때까지 기다린다.
3) 여러 페이지 요소 대기하기 위해 WebDriverWait 개체를 사용한다.

4) 반복문을 사용하여 예외를 잡아낸다. -> 성능이 떨어지고 변화에 탄력적이지 않다.

Final Review

@Test
public void testUserSignupLoginAndSubmitMessage() {
    String username = "pzastoup";
    String password = "whatabadpassword";
    String messageText = "Hello!";

    driver.get(baseURL + "/signup");

    SignupPage signupPage = new SignupPage(driver);
    signupPage.signup("Peter", "Zastoupil", username, password);

    driver.get(baseURL + "/login");

    LoginPage loginPage = new LoginPage(driver);
    loginPage.login(username, password);

    ChatPage chatPage = new ChatPage(driver);
    chatPage.sendChatMessage(messageText);

    ChatMessage sentMessage = chatPage.getFirstMessage();

    assertEquals(username, sentMessage.getUsername());
    assertEquals(messageText, sentMessage.getMessageText());
}
profile
공부일기

0개의 댓글

관련 채용 정보