Start learning free

LESSON 133 OF 173 · BACKEND: TESTS AND RUNNING IT

Your First Test

Practice

Until now you checked your shop by hand: send a request, read the answer, decide if it's right. A test is code that does this for you, every time you run it, so you notice at once when a change breaks something. The course gives you a small test kit modelled on JUnit, Java's best-known test library.

Tests live in a class that extends TestCase. Each method whose name starts with test is one test, and assertEquals(expected, actual) checks that two values are equal: if they differ, the test fails and shows both. Here is a test for a small method, not for the shop:

class ShippingTests extends TestCase {
    static int addShipping(int price) {
        return price + 5;
    }

    void testAddShipping() {
        assertEquals(15, addShipping(10));
    }
}

A test client sends requests to the shop under test. new TestRestTemplate() makes one, and client.getForEntity(path, String.class) sends a GET and gives back the whole answer as a ResponseEntity, with the status in response.getStatusCode().value(). It gives back error statuses too, instead of throwing. The shop answers GET /products with 200 and its four products. The check runs your test on the shop, then on a broken copy that lost its GET /products route, and must print:

Your tests on the shop:
  testProductsAnswer200 ... ok
  1 test: OK
Your tests on a copy that lost its GET /products route:
  testProductsAnswer200 ... FAIL
    AssertionError: expected: <200> but was: <405>
  1 test: 1 failed, so they caught this bug

Your task: write the class ProductTests with one test, testProductsAnswer200, that sends GET /products with a TestRestTemplate and checks that the status code is 200.


Assignment
Follow the Coding Tutorial to write your first test: a class, a test method, a test client, a request and one check.


Hint
In assertEquals, put what you expect first and what you got second. A test with no check passes on any shop, even a broken one, so don't forget the last line.


STEP 1 OF 5
    Ctrl + Enter to check