amigoscode / full-stack-professional

https://amigoscode.com/courses/full-stack-professional
432 stars 205 forks source link

selectCustomerById Test #8

Open hazartilirot opened 1 year ago

hazartilirot commented 1 year ago

That's really strange! We've got a block @BeforeEach setup.... why don't we place the piece of code into it?

var customer = new Customer(
                FAKER.name().fullName(),
                FAKER.internet().safeEmailAddress(),
                new Random().nextInt(18, 99)
        );

customerJDBCDataAccessServiceUnitTest.insertCustomer(customer);

Why does he use the email address to find the customer we've just inserted? He basically relies on a method he hasn't tested yet. It's a shame!

If the previous test is passed we mainly need to rely on it instead.

    @Test
    void selectCustomerById() {
        var customer1 = customerJDBCDataAccessServiceUnitTest.selectAllCustomers()
                                                             .stream()
                                                             .findAny()
                                                             .orElseThrow();
        var customer2 = customerJDBCDataAccessServiceUnitTest.selectCustomerById(customer1.getId())
                                                             .orElseThrow();
        assertThat(customer1.getId()).isEqualTo(customer2.getId());

    }

We don't care what email our inserted user has.... All we care about is if there is a user at all. We get the user and then we test our method looking the user by its ID. Here is the code:

@BeforeEach
    void setUp() {
        customerJDBCDataAccessServiceUnitTest = new CustomerJDBCDataAccessService(getJdbcTemplate());

        var customer = new Customer(
                FAKER.name().fullName(),
                FAKER.internet().safeEmailAddress(),
                new Random().nextInt(18, 99)
        );

        customerJDBCDataAccessServiceUnitTest.insertCustomer(customer);
    }

    @Test
    void selectAllCustomers() {

        var customers = customerJDBCDataAccessServiceUnitTest.selectAllCustomers();

        assertThat(customers).isNotEmpty();
    }

    @Test
    void selectCustomerById() {
        var customer1 = customerJDBCDataAccessServiceUnitTest.selectAllCustomers()
                                                             .stream()
                                                             .findAny()
                                                             .orElseThrow();
        var customer2 = customerJDBCDataAccessServiceUnitTest.selectCustomerById(customer1.getId())
                                                             .orElseThrow();
        assertThat(customer1.getId()).isEqualTo(customer2.getId());

    }