tranvanhumg / web-auto-basic

web-auto-basic
0 stars 0 forks source link

Bài 03 - Hướng dẫn sử dụng JUnit/Hamcrest/assertj để kiểm tra kết quả test #3

Open thienphuong opened 5 years ago

thienphuong commented 5 years ago

Trong Bài 01: Để kiểm tra kết quả mong đợi. chúng ta đã dùng JUnit

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;

.....
// So sánh bằng 
assertEquals(acutalTile, actualExpect); 

....
// So sánh khác 
assertNotEquals(actualString, expectedString);

....
// Kiểm tra có chứa kết quả mong đợi
assertTrue(actualString.contains(expectedString));
thienphuong commented 5 years ago

Cách thứ 2, chúng ta có thể sử dụng Hamcrest, thư viện này đã có sẵn trong JUnit

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;

import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.Is.not;

.....
// So sánh bằng 
assertThat(actual, is(equalTo(expected)));

....
// So sánh khác 
assertThat(actual, is(not(equalTo(expected))));

....
// Kiểm tra có chứa kết quả mong đợi
assertThat(acutalTitle, containsString(actualExpect));

So sánh giữa hai cách viết trên thì cách dùng Hamcrest vs Junit thì nó có một số lợi ích sau:

.... Tham khảo thêm tại đây

thienphuong commented 5 years ago

Cách thứ 3 sử dụng assertj | tài liệu mới nhất

Để sử dụng thư viện này, đảm bảo rằng trong pom.xml đã add thêm dependency sau

<dependency>
  <groupId>org.assertj</groupId>
  <artifactId>assertj-core</artifactId>
  <version>3.6.2</version>
  <scope>test</scope>
</dependency>

Mã chương trình sẽ giống như mẫu sau

import static org.assertj.core.api.Assertions.assertThat;

.....
// So sánh bằng 
assertThat(actual).isEqualTo(expected);

....
// So sánh khác 
assertThat(actual).contains(expected);

....
// Kiểm tra có chứa kết quả mong đợi
assertThat(actual). isNotEqualTo(expected);

... Tham khảo thêm tại đây hoặc xem các example

So sánh Hamcrest vs assertj

Sách tham khảo

thienphuong commented 5 years ago

Ngoài ra có thể tham khảo thêm Truth của google

tranvanhumg commented 5 years ago

Tránh được lỗi run-time assertEquals("abc", 123); chương trình vẫn biên dịch nhưng khi chạy sẽ báo lỗi assertThat(123, is("abc"));Báo lỗi biên dịch

em chạy thử 2 trường hợp này nó đều run thầy ạ Untitled2

tranvanhumg commented 5 years ago

Sao của em lại bị gạch như thế này vậy thầy?

Untitled3

thienphuong commented 5 years ago

Không sao cả. Đơn giản nó để @Deprecated trong source code. Nghiã là unused. Không còn được dùng nữa. Với phiên bản sau này, nó không khuyến kích dùng nó nữa.