forked from eatvio/eatvio_app
refactor(tests): update model instantiation to use const for improved performance
This commit is contained in:
@@ -0,0 +1,241 @@
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:eatvio_app/features/registration_v2/cubit/registration_cubit.dart';
|
||||
import 'package:eatvio_app/features/registration_v2/repositories/registration_repository_v2.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:mockito/annotations.dart';
|
||||
import 'package:mockito/mockito.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
import 'registration_cubit_v2_test.mocks.dart';
|
||||
|
||||
@GenerateMocks([RegistrationRepositoryV2])
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
group('RegistrationCubitV2', () {
|
||||
late RegistrationCubitV2 cubit;
|
||||
late MockRegistrationRepositoryV2 mockRepository;
|
||||
const MethodChannel passwordGeneratorChannel = MethodChannel('flutter_password_generator');
|
||||
|
||||
setUp(() {
|
||||
mockRepository = MockRegistrationRepositoryV2();
|
||||
cubit = RegistrationCubitV2(registrationRepository: mockRepository);
|
||||
|
||||
// Инициализируем SharedPreferences для тестов
|
||||
SharedPreferences.setMockInitialValues({});
|
||||
|
||||
// Мокируем MethodChannel для flutter_password_generator
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(
|
||||
passwordGeneratorChannel,
|
||||
(MethodCall methodCall) async {
|
||||
if (methodCall.method == 'generateSecureRandomData') {
|
||||
// Возвращаем Uint8List для генерации пароля
|
||||
// MethodChannel автоматически преобразует Uint8List в List<int>
|
||||
return Uint8List.fromList(List<int>.generate(32, (i) => i % 256));
|
||||
}
|
||||
return null;
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
tearDown(() {
|
||||
cubit.close();
|
||||
// Очищаем моки
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(
|
||||
passwordGeneratorChannel,
|
||||
null,
|
||||
);
|
||||
});
|
||||
|
||||
test('начальное состояние', () {
|
||||
expect(cubit.state.firstName, isEmpty);
|
||||
expect(cubit.state.lastName, isEmpty);
|
||||
expect(cubit.state.email, isEmpty);
|
||||
expect(cubit.state.phone, isEmpty);
|
||||
expect(cubit.state.gender, isEmpty);
|
||||
expect(cubit.state.step, 0);
|
||||
});
|
||||
|
||||
test('setFirstName - устанавливает имя и валидирует', () {
|
||||
cubit.setFirstName('John');
|
||||
|
||||
expect(cubit.state.firstName, equals('John'));
|
||||
expect(cubit.state.isFirstNameValid, isTrue);
|
||||
});
|
||||
|
||||
test('setFirstName - валидация пустого имени', () {
|
||||
cubit.setFirstName('');
|
||||
|
||||
expect(cubit.state.isFirstNameValid, isFalse);
|
||||
});
|
||||
|
||||
test('setLastName - устанавливает фамилию и валидирует', () {
|
||||
cubit.setLastName('Doe');
|
||||
|
||||
expect(cubit.state.lastName, equals('Doe'));
|
||||
expect(cubit.state.isLastNameValid, isTrue);
|
||||
});
|
||||
|
||||
test('setEmail - устанавливает email и валидирует', () {
|
||||
cubit.setEmail('test@example.com');
|
||||
|
||||
expect(cubit.state.email, equals('test@example.com'));
|
||||
expect(cubit.state.isEmailValid, isTrue);
|
||||
});
|
||||
|
||||
test('setPhone - устанавливает телефон и валидирует', () {
|
||||
cubit.setPhone('+1234567890');
|
||||
|
||||
expect(cubit.state.phone, equals('+1234567890'));
|
||||
expect(cubit.state.isPhoneValid, isTrue);
|
||||
});
|
||||
|
||||
test('setGender - устанавливает пол и валидирует', () {
|
||||
cubit.setGender('male');
|
||||
|
||||
expect(cubit.state.gender, equals('male'));
|
||||
expect(cubit.state.isGenderValid, isTrue);
|
||||
});
|
||||
|
||||
test('setWeight - устанавливает вес и валидирует', () {
|
||||
cubit.setWeight(70);
|
||||
|
||||
expect(cubit.state.weight, equals(70));
|
||||
expect(cubit.state.isWeightValid, isTrue);
|
||||
});
|
||||
|
||||
test('setWeight - валидация нулевого веса', () {
|
||||
cubit.setWeight(0);
|
||||
|
||||
expect(cubit.state.isWeightValid, isFalse);
|
||||
});
|
||||
|
||||
test('setHeight - устанавливает рост и валидирует', () {
|
||||
cubit.setHeight(175);
|
||||
|
||||
expect(cubit.state.height, equals(175));
|
||||
expect(cubit.state.isHeightValid, isTrue);
|
||||
});
|
||||
|
||||
test('setActivityCoefficient - устанавливает коэффициент активности', () {
|
||||
cubit.setActivityCoefficient(1.5);
|
||||
|
||||
expect(cubit.state.activityCoefficient, equals(1.5));
|
||||
expect(cubit.state.isActivityCoefficientValid, isTrue);
|
||||
});
|
||||
|
||||
test('setBirthday - устанавливает дату рождения и валидирует', () {
|
||||
final birthday = DateTime(1990, 1, 1);
|
||||
cubit.setBirthday(birthday);
|
||||
|
||||
expect(cubit.state.birthday, equals(birthday));
|
||||
expect(cubit.state.isBirthdayValid, isTrue);
|
||||
});
|
||||
|
||||
test('nextStep - переходит на следующий шаг', () {
|
||||
cubit.nextStep();
|
||||
|
||||
expect(cubit.state.step, equals(1));
|
||||
});
|
||||
|
||||
test('prevStep - возвращается на предыдущий шаг', () {
|
||||
cubit.nextStep();
|
||||
cubit.prevStep();
|
||||
|
||||
expect(cubit.state.step, equals(0));
|
||||
});
|
||||
|
||||
test('validateAllFields - возвращает true, если все поля валидны', () {
|
||||
cubit.setFirstName('John');
|
||||
cubit.setLastName('Doe');
|
||||
cubit.setEmail('test@example.com');
|
||||
cubit.setPhone('+1234567890');
|
||||
cubit.setGender('male');
|
||||
cubit.setWeight(70);
|
||||
cubit.setHeight(175);
|
||||
cubit.setActivityCoefficient(1.5);
|
||||
cubit.setBirthday(DateTime(1990, 1, 1));
|
||||
|
||||
final result = cubit.validateAllFields();
|
||||
|
||||
expect(result, isTrue);
|
||||
});
|
||||
|
||||
test('validateAllFields - возвращает false, если есть невалидные поля', () {
|
||||
cubit.setFirstName(''); // Пустое имя
|
||||
|
||||
final result = cubit.validateAllFields();
|
||||
|
||||
expect(result, isFalse);
|
||||
});
|
||||
|
||||
test('register - успешная регистрация', () async {
|
||||
cubit.setFirstName('John');
|
||||
cubit.setLastName('Doe');
|
||||
cubit.setEmail('test@example.com');
|
||||
cubit.setPhone('+1234567890');
|
||||
cubit.setGender('male');
|
||||
cubit.setWeight(70);
|
||||
cubit.setHeight(175);
|
||||
cubit.setActivityCoefficient(1.5);
|
||||
cubit.setBirthday(DateTime(1990, 1, 1));
|
||||
|
||||
const token = 'test-token';
|
||||
when(mockRepository.register(registrationModel: anyNamed('registrationModel')))
|
||||
.thenAnswer((_) async => token);
|
||||
|
||||
final result = await cubit.register();
|
||||
|
||||
expect(result.$1, isTrue);
|
||||
expect(result.$2, isFalse);
|
||||
verify(mockRepository.register(registrationModel: anyNamed('registrationModel'))).called(1);
|
||||
});
|
||||
|
||||
test('register - возвращает false при невалидных полях', () async {
|
||||
cubit.setFirstName(''); // Пустое имя
|
||||
|
||||
final result = await cubit.register();
|
||||
|
||||
expect(result.$1, isFalse);
|
||||
expect(result.$2, isTrue);
|
||||
verifyNever(mockRepository.register(registrationModel: anyNamed('registrationModel')));
|
||||
});
|
||||
|
||||
test('register - обработка ошибки валидации email', () async {
|
||||
cubit.setFirstName('John');
|
||||
cubit.setLastName('Doe');
|
||||
cubit.setEmail('test@example.com');
|
||||
cubit.setPhone('+1234567890');
|
||||
cubit.setGender('male');
|
||||
cubit.setWeight(70);
|
||||
cubit.setHeight(175);
|
||||
cubit.setActivityCoefficient(1.5);
|
||||
cubit.setBirthday(DateTime(1990, 1, 1));
|
||||
|
||||
final dioException = DioException(
|
||||
requestOptions: RequestOptions(path: '/'),
|
||||
response: Response(
|
||||
requestOptions: RequestOptions(path: '/'),
|
||||
statusCode: 422,
|
||||
data: {
|
||||
'errors': {
|
||||
'email': ['Некорректный формат email'],
|
||||
},
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
when(mockRepository.register(registrationModel: anyNamed('registrationModel')))
|
||||
.thenThrow(dioException);
|
||||
|
||||
final result = await cubit.register();
|
||||
|
||||
expect(result.$1, isFalse);
|
||||
expect(result.$2, isTrue);
|
||||
expect(cubit.state.isEmailValid, isFalse);
|
||||
expect(cubit.state.emailDisplayError, equals('Некорректный формат email'));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
import 'package:eatvio_app/features/registration_v2/models/registration_model.dart';
|
||||
import 'package:eatvio_app/features/registration_v2/repositories/registration_repository_v2.dart';
|
||||
import 'package:eatvio_app/features/registration_v2/services/registration_service_v2.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:mockito/annotations.dart';
|
||||
import 'package:mockito/mockito.dart';
|
||||
|
||||
import 'registration_repository_v2_test.mocks.dart';
|
||||
|
||||
@GenerateMocks([RegistrationServiceV2])
|
||||
void main() {
|
||||
group('RegistrationRepositoryV2', () {
|
||||
late RegistrationRepositoryV2 repository;
|
||||
late MockRegistrationServiceV2 mockService;
|
||||
|
||||
setUp(() {
|
||||
mockService = MockRegistrationServiceV2();
|
||||
repository = RegistrationRepositoryV2(registrationService: mockService);
|
||||
});
|
||||
|
||||
test('register - успешная регистрация', () async {
|
||||
final registrationModel = RegistrationModel(
|
||||
firstName: 'John',
|
||||
lastName: 'Doe',
|
||||
email: 'test@example.com',
|
||||
phone: '+1234567890',
|
||||
gender: 'male',
|
||||
password: 'password123',
|
||||
confirmPassword: 'password123',
|
||||
weight: 70,
|
||||
height: 175,
|
||||
activityCoefficient: 1.5,
|
||||
birthday: '1990-01-01',
|
||||
);
|
||||
|
||||
const token = 'test-token';
|
||||
when(mockService.register(model: anyNamed('model')))
|
||||
.thenAnswer((_) async => {'token': token});
|
||||
|
||||
final result = await repository.register(registrationModel: registrationModel);
|
||||
|
||||
expect(result, equals(token));
|
||||
verify(mockService.register(model: anyNamed('model'))).called(1);
|
||||
});
|
||||
|
||||
test('register - проброс ошибки', () async {
|
||||
final registrationModel = RegistrationModel(
|
||||
firstName: 'John',
|
||||
lastName: 'Doe',
|
||||
email: 'test@example.com',
|
||||
phone: '+1234567890',
|
||||
gender: 'male',
|
||||
password: 'password123',
|
||||
confirmPassword: 'password123',
|
||||
weight: 70,
|
||||
height: 175,
|
||||
activityCoefficient: 1.5,
|
||||
birthday: '1990-01-01',
|
||||
);
|
||||
|
||||
final error = Exception('Ошибка регистрации');
|
||||
when(mockService.register(model: anyNamed('model')))
|
||||
.thenThrow(error);
|
||||
|
||||
expect(
|
||||
() => repository.register(registrationModel: registrationModel),
|
||||
throwsA(error),
|
||||
);
|
||||
verify(mockService.register(model: anyNamed('model'))).called(1);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user