JavaRush /Java blogi /Random-UZ /JUnit I qism

JUnit I qism

Guruhda nashr etilgan

JUnit :: yoki JavaRush validatorini qanday sevish kerak

JUnit I qism - 1Nima uchun bizga bu hayvon kerakligi haqida qisqacha ma'lumot? JUnit - bu sizning yaxshi yoki unchalik yaxshi bo'lmagan kodingizni avtomatik ravishda sinab ko'rish uchun ramka . Siz aytishingiz mumkin: - bu belanchak menga nima uchun kerak, men o'zimning yaxshi Java kodimni osongina va oddiygina sinab ko'rishim mumkin. Ko'p kirish so'zlari yozishingiz mumkin, lekin men unchalik shoir emasman, keling, ishga kirishaylik...

Ob'ekt yarating

Shunday qilib, biror narsani sinab ko'rish uchun bizga birinchi navbatda sinov ob'ekti kerak. Bizning oldimizda vazifa turibdi.
  1. Bizga foydalanuvchi haqidagi ma'lumotlarni saqlaydigan ob'ekt kerak.
    1. Id - yangi foydalanuvchi qo'shilgan tartibda hisoblanishi kerak.
    2. Foydalanuvchi nomi.
    3. Uning yoshi.
    4. Jins (erkak/ayol)
  2. Foydalanuvchilar ro'yxatini saqlashni ta'minlash kerak.

  3. Sinf bunga qodir bo'lishi kerak.

    1. Barcha foydalanuvchilar ro'yxatini yarating.
    2. Jins bo‘yicha foydalanuvchilar ro‘yxatini yarating (MALE/FEMALE).
    3. Umumiy ro'yxatdagi foydalanuvchilar sonini qaytaring va foydalanuvchi jinsiga qarab raqamni hisoblang.
    4. Umumiy miqdorni foydalanuvchi yoshi bo'yicha hisoblang, shuningdek, jinsni hisobga oling.
    5. O'rtacha yoshni umumiy va jins bo'yicha hisoblang.
UserShunday qilib, ob'ekt yaratishni boshlaymiz... Maydonlarni o'z ichiga olgan Java sinfini yaratamiz :
private int id;
private String name;
private int age;
private Sex sex;
Bu foydalanuvchi ma'lumotlarini saqlash uchun etarli, keling, vazifa uchun yana nima kerakligini ko'rib chiqaylik. Biz qandaydir tarzda barcha foydalanuvchilarni saqlashimiz kerak, keling, sinfimizda statik maydon yarataylik allUsers, agar shunday bo'lsa, yaxshi deb o'ylayman.Map<Integer, User>
private static Map<Integer, User> allUsers;
Shuningdek, foydalanuvchilarga qandaydir tarzda tartib raqamini belgilashimiz kerak, keling, yangi foydalanuvchi yaratishda Id foydalanuvchiga tartib raqamini beradigan statik hisoblagich maydonini yarataylik.
private static int countId = 0;
Shunday qilib, biz maydonlarni saralab oldik shekilli, ob'ektimiz uchun konstruktor va , , , idmaydonlari nameuchun getters yozamiz . Heterae bilan hech qanday murakkab narsa yo'q, keling, IDEA dan yordam so'raylik , u hech qachon rad etmaydi va biz konstruktorni biroz qiyinlashtiramiz. Dizayner buni qila oladi. Maydonlarni ishga tushiring, ichida bunday ob'ekt mavjudligini tekshiring , agar bunday ob'ekt bo'lmasa, hisoblagichimizni oshiring va uni barcha foydalanuvchilar ro'yxatiga qo'shing. Shuningdek , agar u hali ishga tushirilmagan bo'lsa, maydonni ishga tushiring . Bir xil ob'ektlarni qidirish qulayligi uchun biz usullarni qayta aniqlaymiz va yana sevimli IDEA dan yordam so'raymiz va maydonlar bo'yicha solishtiramiz , , . Bundan tashqari, keling, bunday ob'ektning ro'yxatda mavjudligini tekshiradigan shaxsiy usul yarataylik .agesexallUserscountId++allUsers equals()hashCode()nameagesexhasUser()
@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;
    User user = (User) o;
    return age == user.age &&
            Objects.equals(name, user.name) &&
            sex == user.sex;
}

@Override
public int hashCode() {

    return Objects.hash(name, age, sex);
}
Oxir-oqibat, men shunday dizaynerga ega bo'ldim.
public User(String name, int age, Sex sex) {
    if (allUsers == null){
        allUsers = new HashMap<>();
    }

    this.name = name;
    this.age = age;
    this.sex = sex;

    if (!hasUser()){
        countId++;
        this.id = countId;
        allUsers.put(id, this);
    }
}
va shaxsiy yordamchi usuli
private boolean hasUser(){
    for (User user : allUsers.values()){
        if (user.equals(this) && user.hashCode() == this.hashCode()){
            return true;
        }
    }
    return false;
}
va yana aniqlangtoString()
@Override
public String toString() {
    return "User{" +
            "id=" + id +
            ", name='" + name + '\'' +
            ", age=" + age +
            ", sex=" + sex +
            '}';
}
Endi kerakli usullarning mantiqini amalga oshirish vaqti keldi. Mantiq asosan statik maydonlar bilan ishlaganligi sababli, biz usullarni ham statik qilamiz, ular ob'ektlar uchun kerak emas.
  1. Barcha foydalanuvchilar ro'yxatini yarating.
  2. Jins bo‘yicha foydalanuvchilar ro‘yxatini yarating (MALE/FEMALE).
  3. a va b nuqtalari getAllUsers()barcha ro'yxatini qaytaradigan usul va o'tkazilgan parametrga qarab ro'yxatni qaytaradigan Userortiqcha yuklangan usul bilan yaxshi ishlov berilishi mumkin .getAllUsers(Sex sex)Sex

    public static List<User> getAllUsers(){
        return new ArrayList<>(allUsers.values());
    }
    
    public static List<User> getAllUsers(Sex sex){
        List<User> listAllUsers = new ArrayList<>();
        for (User user : allUsers.values()){
            if (user.sex == sex){
                listAllUsers.add(user);
            }
        }
        return listAllUsers;
    }

  4. Umumiy ro'yxatdagi foydalanuvchilar sonini qaytaring va foydalanuvchi jinsiga qarab raqamni hisoblang.

    public static int getHowManyUsers(){
        return allUsers.size();
    }
    
    public static int getHowManyUsers(Sex sex){
        return getAllUsers(sex).size();
    }

  5. Umumiy miqdorni foydalanuvchi yoshi bo'yicha hisoblang, shuningdek, jinsni hisobga oling. Keling, ushbu vazifa uchun usullarni yarataylik.

    public static int getAllAgeUsers(){
        int countAge = 0;
        for (User user : allUsers.values()){
            countAge += user.age;
        }
        return countAge;
    }
    
    public static int getAllAgeUsers(Sex sex){
        int countAge = 0;
        for (User user : getAllUsers(sex)){
            countAge += user.age;
        }
        return countAge;
    }

  6. O'rtacha yoshni umumiy va jins bo'yicha hisoblang.

    public static int getAverageAgeOfAllUsers(){
        return getAllAgeUsers() / getHowManyUsers();
    }
    
    public static int getAverageAgeOfAllUsers(Sex sex){
        return getAllAgeUsers(sex) / getHowManyUsers(sex);
    }

    Ajoyib, biz kerakli ob'ektni va uning xatti-harakatlarini tasvirlab berdik. Endi biz JUnit- ga o'tishimiz mumkin , lekin birinchi navbatda, agar biz buni main -da qilsak, oddiy test qanday ko'rinishini ko'rsataman .

    public static void main(String[] args) {
        new User("Eugene", 35, Sex.MALE);
        new User("Marina", 34, Sex.FEMALE);
        new User("Alina", 7, Sex.FEMALE);
    
    
        System.out.println("All users:");
        User.getAllUsers().forEach(System.out::println);
        System.out.println("All users: MALE");
        User.getAllUsers(Sex.MALE).forEach(System.out::println);
        System.out.println("All users: FEMALE");
        User.getAllUsers(Sex.FEMALE).forEach(System.out::println);
        System.out.println("================================================");
        System.out.println(" all users: " + User.getHowManyUsers());
        System.out.println(" all MALE users: " + User.getHowManyUsers(Sex.MALE));
        System.out.println("all FEMALE users: " + User.getHowManyUsers(Sex.FEMALE));
        System.out.println("================================================");
        System.out.println(" total age of all users: " + User.getAllAgeUsers());
        System.out.println(" total age of all MALE users: " + User.getAllAgeUsers(Sex.MALE));
        System.out.println("total age of all FEMALE users: " + User.getAllAgeUsers(Sex.FEMALE));
        System.out.println("================================================");
        System.out.println(" average age of all users: " + User.getAverageAgeOfAllUsers());
        System.out.println(" average age of all MALE users: " + User.getAverageAgeOfAllUsers(Sex.MALE));
        System.out.println("average age of all FEMALE users: " + User.getAverageAgeOfAllUsers(Sex.FEMALE));
        System.out.println("================================================");
    }

    Konsolga chiqadigan ma'lumotlar shunga o'xshash bo'ladi va keyin biz normal ishlayotganimizni taqqoslaymiz. Biz, albatta, chuqurroq borishimiz, taqqoslash mantig'ini yozishimiz va hisob-kitobimiz nima ekanligini ko'rishimiz mumkin, garchi biz hamma narsani ta'minlay olganimizga ishonchimiz komil bo'lmasa ham.

    //output
    Все пользователи:
    User{id=1, name='Eugene', age=35, sex=MALE}
    User{id=2, name='Marina', age=34, sex=FEMALE}
    User{id=3, name='Alina', age=7, sex=FEMALE}
    Все пользователи: MALE
    User{id=1, name='Eugene', age=35, sex=MALE}
    Все пользователи: FEMALE
    User{id=2, name='Marina', age=34, sex=FEMALE}
    User{id=3, name='Alina', age=7, sex=FEMALE}
    ================================================
           всех пользователей: 3
      всех пользователей MALE: 1
    всех пользователей FEMALE: 2
    ================================================
           общий возраст всех пользователей: 76
      общий возраст всех пользователей MALE: 35
    общий возраст всех пользователей FEMALE: 41
    ================================================
           средний возраст всех пользователей: 25
      средний возраст всех пользователей MALE: 35
    средний возраст всех пользователей FEMALE: 20
    ================================================
    
    Process finished with exit code 0

    Biz bu natijadan mamnun emasmiz, asosiy testlar bilan, bizga JUnit kerak .

JUnitni loyihaga qanday ulash mumkin

Uni loyihaga qanday ulash kerak degan savol tug'iladi. Bilganlar uchun men Maven bilan variantni tanlamayman , chunki bu butunlay boshqacha hikoya. ;) Loyiha strukturasini oching Ctrl + Alt + Shift + S -> Libraries -> tugmasini bosing + (New Project Library) -> Maven dan tanlang, JUnit I qism - 2keyin shunday oynani ko'ramiz, qidiruv satriga “junit:junit:4.12” kiriting. , topilguncha kuting -> OK! -> OK! JUnit I qism - 3Siz ushbu natijani olishingiz kerak JUnit I qism - 4OK tugmasini bosing, tabriklaymiz JUnit loyihaga qo'shildi. Keling, davom etaylik. Endi biz Java sinfimiz uchun testlar yaratishimiz kerak, kursorni sinf nomiga qo'ying User -> Alt + Enter ni bosing -> Test yaratish ni tanlang. Biz JUnit4 kutubxonasini tanlashimiz kerak bo'lgan oynani ko'rishimiz kerak -> biz sinab ko'rmoqchi bo'lgan usullarni tanlang -> OK JUnit I qism - 5G'oyaning o'zi sinf yaratadi UserTest, bu biz kodimizni testlar bilan qamrab oladigan sinfdir. Qani boshladik:

Bizning birinchi @Test

Keling, birinchi @Test usulimizni yarataylik getAllUsers()- bu barcha foydalanuvchilarni qaytarishi kerak bo'lgan usul. Sinov quyidagicha ko'rinadi:
@Test
public void getAllUsers() {
    // create test data
    User user = new User("Eugene", 35, Sex.MALE);
    User user1 = new User("Marina", 34, Sex.FEMALE);
    User user2 = new User("Alina", 7, Sex.FEMALE);

    //create an expected list and fill it with the data of our method
    List<User> expected = User.getAllUsers();

    //create actual list put data in it for comparison
    //what we expect the method to return
    List<User> actual = new ArrayList<>();
    actual.add(user);
    actual.add(user1);
    actual.add(user2);

    //run the test if the list expected and actual are not equal
    //the test will fail, read the test results in the console
    Assert.assertEquals(expected, actual);
}
Bu erda biz bir nechta test foydalanuvchilarini yaratamiz -> expected usuli bizga qaytib keladigan foydalanuvchilarni joylashtirgan ro'yxatni yaratamiz -> Assert.assertEquals (haqiqiy, kutilgan) usuli deb hisoblagan foydalanuvchilarni joylashtiradigan getAllUsers()ro'yxat yaratamiz. foydalaniladi va biz tekshirilgan va joriy qilingan ro'yxatlarni unga o'tkazamiz. Ushbu usul taqdim etilgan ro'yxatlardagi ob'ektlarni sinab ko'radi va test natijasini qaytaradi. Usul ob'ektlarning barcha maydonlarini, hatto meros bo'lsa, ota-onalarning maydonlarini ham taqqoslaydi. Keling, birinchi testni o'tkazamiz ... Test muvaffaqiyatli yakunlandi. Keling, testni muvaffaqiyatsiz qilishga harakat qilaylik, buning uchun test ro'yxatlaridan birini o'zgartirishimiz kerak, biz buni ro'yxatga bitta foydalanuvchi qo'shilishi haqida izoh berish orqali qilamiz . actual getAllUsers()JUnit I qism - 6actual
@Test
public void getAllUsers() {
    // create test data
    User user = new User("Eugene", 35, Sex.MALE);
    User user1 = new User("Marina", 34, Sex.FEMALE);
    User user2 = new User("Alina", 7, Sex.FEMALE);

    //create an expected list and fill it with the data of our method
    List<User> expected = User.getAllUsers();

    //create actual list put data in it for comparison
    //what we expect the method to return
    List<User> actual = new ArrayList<>();
    actual.add(user);
    actual.add(user1);
    //actual.add(user2);

    //run the test if the list expected and actual are not equal
    //the test will fail, read the test results in the console
    Assert.assertEquals(expected, actual);
}
biz testni o'tkazamiz va quyidagilarni ko'ramiz: JUnit I qism - 7Endi biz testning muvaffaqiyatsizligi sababini biroz ko'rib chiqamiz. Bu erda biz tekshirilgan ro'yxatda joriy ro'yxatga qaraganda ko'proq foydalanuvchilar borligini ko'ramiz. Bu muvaffaqiyatsizlikning sababi. Buni asosiyda tekshira olamizmi? JUnit : main = 1 : 0. Keling, test qanday ko'rinishini ko'rib chiqaylik, agar u butunlay boshqa ob'ektlarni o'z ichiga olsa, buni quyidagicha bajaramiz:
@Test
public void getAllUsers() {
    // create test data
    User user = new User("Eugene", 35, Sex.MALE);
    User user1 = new User("Marina", 34, Sex.FEMALE);
    User user2 = new User("Alina", 7, Sex.FEMALE);

    //create an expected list and fill it with the data of our method
    List<User> expected = User.getAllUsers();

    //create actual list put data in it for comparison
    //what we expect the method to return
    List<User> actual = new ArrayList<>();
    actual.add(new User("User1", 1, Sex.MALE));
    actual.add(new User("User2", 2, Sex.FEMALE));
    actual.add(new User("User3", 3, Sex.MALE));

    //run the test if the list expected and actual are not equal
    //the test will fail, read the test results in the console
    Assert.assertEquals(expected, actual);
}
Bu konsolda bo'ladi: JUnit I qism - 8bu erda siz taqqoslangan ro'yxatlarda turli xil foydalanuvchilar borligini darhol ko'rishingiz mumkin, biz farqni ko'rish uchun <Click tugmasini bosishimiz mumkin> bizda qanday ma'lumotlar borligini batafsil ko'rishimiz mumkin bo'lgan oyna paydo bo'ladi. bilan muammo. IDEA farqlar mavjud bo'lgan barcha maydonlarni ajratib ko'rsatadi. JUnit I qism - 9mainbu sodir bo'lishi mumkinmi? - Yo'q. getAllUsers()JUnit : main = 2 : 0 Xo'sh, davom etaylik, bizda hali testlar bilan qamrab olinishi kerak bo'lgan bir qancha usullar mavjud), ammo kuting, usul bizga qaytib keladimi yoki yo'qligini tekshirish yomon bo'lmaydi , chunki bu validator tomonidan ushlangan JavaRushnull vazifalari bilan nima qilamiz). Keling, buni qilaylik, bu uch tiyin masalasi ...
@Test
public void getAllUsers_NO_NULL() {
    //add check for null
    List<User> expected = User.getAllUsers();
    Assert.assertNotNull(expected);
}
Ha, ha, validator bizning shiddatli kodimizni taxminan shunday ushlaydi null;) Keling, ushbu testni bajaramiz va u bizga nimani ko'rsatayotganini ko'rib chiqamiz. Va u xatoni ko'rsatadi, qanday qilib???? Qanday qilib bu erda test xatosi bo'lishi mumkin))) JUnit I qism - 10Va bu erda biz kodimizni testlar bilan qoplashning birinchi mevasini olishimiz mumkin. Esingizda bo'lsa, allUsers biz konstruktorda maydonni ishga tushirdik, ya'ni usulni chaqirganda getAllUsers(), biz hali ishga tushirilmagan ob'ektga murojaat qilamiz. Keling, uni tahrirlaymiz, konstruktordan initsializatsiyani olib tashlaymiz va maydonni e'lon qilishda buni qilamiz.
private static Map<Integer, User> allUsers = new HashMap<>();

    public User(String name, int age, Sex sex) {
        this.name = name;
        this.age = age;
        this.sex = sex;

        if (!hasUser()) {
            countId++;
            this.id = countId;
            allUsers.put(id, this);
        }
    }
Keling, testni o'tkazamiz, endi hamma narsa yaxshi. JUnit I qism - 11Asosiy NPElarni qo'lga olish oson bo'lmaydi deb o'ylayman, menimcha, siz JUnit hisobiga rozi bo'lasiz: main = 3: 0 Keyin men barcha usullarni testlar bilan qamrab olaman va qanday ko'rinishini ko'raman ... Endi bizning test sinfimiz quyidagicha ko'rinadi:
package user;

import org.junit.Assert;
import org.junit.Test;

import java.util.ArrayList;
import java.util.List;

import static org.junit.Assert.*;

public class UserTest {

    @Test
    public void getAllUsers() {
        // create test data
        User user = new User("Eugene", 35, Sex.MALE);
        User user1 = new User("Marina", 34, Sex.FEMALE);
        User user2 = new User("Alina", 7, Sex.FEMALE);

        //create an expected list and fill it with the data of our method
        List<User> expected = User.getAllUsers();

        //create actual list put data in it for comparison
        //what we expect the method to return
        List<User> actual = new ArrayList<>();
        actual.add(user);
        actual.add(user1);
        actual.add(user2);

        //run the test if the list expected and actual are not equal
        //the test will fail, read the test results in the console
        Assert.assertEquals(expected, actual);
    }

    @Test
    public void getAllUsers_NO_NULL() {
        //add check for null
        List<User> expected = User.getAllUsers();
        Assert.assertNotNull(expected);
    }

    @Test
    public void getAllUsers_MALE() {
        User user = new User("Eugene", 35, Sex.MALE);
        User user1 = new User("Marina", 34, Sex.FEMALE);
        User user2 = new User("Alina", 7, Sex.FEMALE);

        List<User> expected = User.getAllUsers(Sex.MALE);

        List<User> actual = new ArrayList<>();
        actual.add(user);

        Assert.assertEquals(expected, actual);
    }

    @Test
    public void getAllUsers_MALE_NO_NULL() {
        //add check for null
        List<User> expected = User.getAllUsers(Sex.MALE);
        Assert.assertNotNull(expected);
    }

    @Test
    public void getAllUsers_FEMALE() {
        User user = new User("Eugene", 35, Sex.MALE);
        User user1 = new User("Marina", 34, Sex.FEMALE);
        User user2 = new User("Alina", 7, Sex.FEMALE);

        List<User> expected = User.getAllUsers(Sex.FEMALE);

        List<User> actual = new ArrayList<>();
        actual.add(user1);
        actual.add(user2);

        Assert.assertEquals(expected, actual);
    }

    @Test
    public void getAllUsers_FEMALE_NO_NULL() {
        //add check for null
        List<User> expected = User.getAllUsers(Sex.FEMALE);
        Assert.assertNotNull(expected);
    }

    @Test
    public void getHowManyUsers() {
        User user = new User("Eugene", 35, Sex.MALE);
        User user1 = new User("Marina", 34, Sex.FEMALE);
        User user2 = new User("Alina", 7, Sex.FEMALE);

        int expected = User.getHowManyUsers();

        int actual = 3;

        Assert.assertEquals(expected, actual);
    }

    @Test
    public void getHowManyUsers_MALE() {
        User user = new User("Eugene", 35, Sex.MALE);
        User user1 = new User("Marina", 34, Sex.FEMALE);
        User user2 = new User("Alina", 7, Sex.FEMALE);

        int expected = User.getHowManyUsers(Sex.MALE);

        int actual = 1;

        Assert.assertEquals(expected, actual);
    }

    @Test
    public void getHowManyUsers_FEMALE() {
        User user = new User("Eugene", 35, Sex.MALE);
        User user1 = new User("Marina", 34, Sex.FEMALE);
        User user2 = new User("Alina", 7, Sex.FEMALE);

        int expected = User.getHowManyUsers(Sex.FEMALE);

        int actual = 2;

        Assert.assertEquals(expected, actual);
    }

    @Test
    public void getAllAgeUsers() {
        User user = new User("Eugene", 35, Sex.MALE);
        User user1 = new User("Marina", 34, Sex.FEMALE);
        User user2 = new User("Alina", 7, Sex.FEMALE);

        int expected = User.getAllAgeUsers();

        int actual = 35 + 34 + 7;

        Assert.assertEquals(expected, actual);
    }

    @Test
    public void getAllAgeUsers_MALE() {
        User user = new User("Eugene", 35, Sex.MALE);
        User user1 = new User("Marina", 34, Sex.FEMALE);
        User user2 = new User("Alina", 7, Sex.FEMALE);

        int expected = User.getAllAgeUsers(Sex.MALE);

        int actual = 35;

        Assert.assertEquals(expected, actual);
    }

    @Test
    public void getAllAgeUsers_FEMALE() {
        User user = new User("Eugene", 35, Sex.MALE);
        User user1 = new User("Marina", 34, Sex.FEMALE);
        User user2 = new User("Alina", 7, Sex.FEMALE);

        int expected = User.getAllAgeUsers(Sex.FEMALE);

        int actual = 34 + 7;

        Assert.assertEquals(expected, actual);
    }
}
Ha, bu kichik emas edi, lekin katta loyihalar bilan ishlashda nima bo'ladi. Bu erda nimani kamaytirish mumkin?Hammasini baholagandan so'ng, biz har bir testda test ma'lumotlarini yaratayotganimizni ko'rishingiz mumkin va bu erda bizga izohlar keladi. Keling, qabul qilaylik @Before- Izoh @Beforehar bir sinovdan o'tgan usuldan oldin usul bajarilishini bildiradi @Test. Endi izohli test sinfimiz shunday ko'rinadi @Before:
package user;

import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

import java.util.ArrayList;
import java.util.List;

import static org.junit.Assert.*;

public class UserTest {
    private User user;
    private User user1;
    private User user2;

    @Before
    public void setUp() throws Exception {
        user = new User("Eugene", 35, Sex.MALE);
        user1 = new User("Marina", 34, Sex.FEMALE);
        user2 = new User("Alina", 7, Sex.FEMALE);
    }

    @Test
    public void getAllUsers() {
        List<User> expected = User.getAllUsers();

        List<User> actual = new ArrayList<>();
        actual.add(user);
        actual.add(user1);
        actual.add(user2);

        Assert.assertEquals(expected, actual);
    }

    @Test
    public void getAllUsers_NO_NULL() {
        List<User> expected = User.getAllUsers();
        Assert.assertNotNull(expected);
    }

    @Test
    public void getAllUsers_MALE() {
        List<User> expected = User.getAllUsers(Sex.MALE);

        List<User> actual = new ArrayList<>();
        actual.add(user);

        Assert.assertEquals(expected, actual);
    }

    @Test
    public void getAllUsers_MALE_NO_NULL() {
        //add check for null
        List<User> expected = User.getAllUsers(Sex.MALE);
        Assert.assertNotNull(expected);
    }

    @Test
    public void getAllUsers_FEMALE() {
        List<User> expected = User.getAllUsers(Sex.FEMALE);

        List<User> actual = new ArrayList<>();
        actual.add(user1);
        actual.add(user2);

        Assert.assertEquals(expected, actual);
    }

    @Test
    public void getAllUsers_FEMALE_NO_NULL() {
        //add check for null
        List<User> expected = User.getAllUsers(Sex.FEMALE);
        Assert.assertNotNull(expected);
    }

    @Test
    public void getHowManyUsers() {
        int expected = User.getHowManyUsers();

        int actual = 3;

        Assert.assertEquals(expected, actual);
    }

    @Test
    public void getHowManyUsers_MALE() {
        int expected = User.getHowManyUsers(Sex.MALE);

        int actual = 1;

        Assert.assertEquals(expected, actual);
    }

    @Test
    public void getHowManyUsers_FEMALE() {
        int expected = User.getHowManyUsers(Sex.FEMALE);

        int actual = 2;

        Assert.assertEquals(expected, actual);
    }

    @Test
    public void getAllAgeUsers() {
        int expected = User.getAllAgeUsers();

        int actual = 35 + 34 + 7;

        Assert.assertEquals(expected, actual);
    }

    @Test
    public void getAllAgeUsers_MALE() {
        int expected = User.getAllAgeUsers(Sex.MALE);

        int actual = 35;

        Assert.assertEquals(expected, actual);
    }

    @Test
    public void getAllAgeUsers_FEMALE() {
        int expected = User.getAllAgeUsers(Sex.FEMALE);

        int actual = 34 + 7;

        Assert.assertEquals(expected, actual);
    }
}
Xo'sh, siz-chi, u allaqachon qiziqarliroq va o'qish osonroq;) Mana JUnit uchun izohlar ro'yxati, ular bilan yashash, albatta, osonroq.
@Test – определяет что метод method() является тестовым.
@Before – указывает на то, что метод будет выполнятся перед каждым тестируемым методом @Test.
@After – указывает на то что метод будет выполнятся после каждого тестируемого метода @Test
@BeforeClass – указывает на то, что метод будет выполнятся в начале всех тестов,
а точней в момент запуска тестов(перед всеми тестами @Test).
@AfterClass – указывает на то, что метод будет выполнятся после всех тестов.
@Ignore – говорит, что метод будет проигнорирован в момент проведения тестирования.
(expected = Exception.class) – указывает на то, что в данном тестовом методе
вы преднамеренно ожидаете Exception.
(timeout = 100) – указывает, что тестируемый метод не должен занимать больше чем 100 миллисекунд.
AssertSinfni tekshirishning asosiy usullari :
fail(String) – указывает на то что бы тестовый метод завалился при этом выводя текстовое сообщение.
assertTrue([message], boolean condition) – проверяет, что логическое condition истинно.
assertsEquals([String message], expected, actual) – проверяет, что два значения совпадают.
Примечание: для массивов проверяются ссылки, а не содержание массивов.
assertNull([message], object) – проверяет, что an object является пустым null.
assertNotNull([message], object) – проверяет, что an object не является пустым null.
assertSame([String], expected, actual) – проверяет, что обе переменные относятся к одному an objectу.
assertNotSame([String], expected, actual) – проверяет, что обе переменные относятся к разным an objectм.
Mavenda JUnit 4.12 qaramligini shu tarzda qo'shishimiz mumkin
<dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <version>4.12</version>
  <scope>test</scope>
</dependency>
Bu erda davom etdi -> JUnit II qism
Izohlar
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION