- Getting started with writing functional test cases in Android
- Types of Software Testing
- What is a Functional Test?
- Why Functional Testing is Required?
- Functional Testing VS Non-Functional Testing
- Advantages of Functional Testing
- Steps to Involved in Functional Testing
- Types of Functional Testing
- Functional Testing Techniques
- Tools for functional Testing
- Тестирование Android приложений
- Введение
- Часть первая. SpeedConverter.
- Часть вторая. SpeedConverterTest.
Getting started with writing functional test cases in Android
Software testing is the process of evaluating and verifying that a software product or application does what it is supposed to do. The benefits of testing include preventing bugs, reducing development costs and improving performance.
Types of Software Testing
- Functional Testing
- Non-Functional Testing
What is a Functional Test?
Functional testing is a type of software testing that validates the software system against the functional requirements/specifications. The purpose of functional tests is to test each function of the software application.
By providing appropriate input, verifying the output against the functional requirements. It is a type of black-box testing as the application’s source code is not considered during the testing process.
Why Functional Testing is Required?
The need for functional testing is vital in validating the quality and functionality of the software.
Through this software testing technique, quality assurance teams verify the software functionality based on the Software Requirements Specification (SRS) and ensure the system functions as per the user specifications.
Functional Testing VS Non-Functional Testing
- Functional testing verifies each function/feature of the software whereas Non Functional testing verifies non-functional aspects like performance, usability, reliability, etc.
- Functional testing helps to enhance the behavior of the application.
- Non-Functional testing helps to improve the performance of the application.
- Functional testing is easy to execute manually.
- Non-Functional testing is hard to execute non-functional testing manually.
Advantages of Functional Testing
- It ensures that the customer or end-user is satisfied.
- It produces a defect-free product/software.
- It ensures the all the requirements should be met.
- It ensures the proper working of all the functionalities of an application/software/product.
- It ensures that the software/product works as expected.
- It ensures security and safety.
- It improves the quality of the product.
- Reduce risks and losses associated with the product/software.
Steps to Involved in Functional Testing
Step1 — The first step is to determine the functionality of a product that needs to be tested.
Step2 — Next step is to create input data for the functionality to be tested as per the requirement specifications.
Step3 — Output is determined for the functionality.
Step4 — Prepared test cases are executed in the next step.
Step5 — Compare the actual and expected output.
Types of Functional Testing
Unit testing:- It is a type of software testing where individual units or components of the software are tested. The purpose is to validate that each unit of the software code performs as expected.
Smoke Testing:- It is a software testing process that determines whether the deployed software build is stable or not. Smoke testing is also known as “Build Verification Testing” or “Confidence Testing.”
System Testing:- It is a level of testing that validates the complete and fully integrated software product. The purpose of a system test is to evaluate the end-to-end system specifications.
User Acceptance Testing(UAT):- It is a type of testing performed by the end-user or the client to verify/accept the software system before moving the software application to the production environment. The main purpose of UAT is to validate end-to-end business flow. It does not focus on cosmetic errors, spelling mistakes or system testing.
Regression Testing: It is defined as a type of software testing to confirm that a recent program or code change has not adversely affected existing features. Regression testing is needed, when a new feature is added to the software application and for defect fixing as well as performance issue fixing.
Integration Testing: It is defined as a type of testing where software modules are integrated logically and tested as a group. A typical software project consists of multiple software modules, coded by different programmers. This level of testing aims to expose defects in the interaction between these software modules when they are integrated.
Functional Testing Techniques
- Positive Testing is a type of testing which is performed on a software application by providing valid data sets as input. It checks whether the software application behaves as expected with positive inputs or not. Positive testing is performed in order to check whether the software application does exactly what it is expected to do.
- Negative Testing is a testing method performed on the software application by providing invalid or improper data sets as input. It checks whether the software application behaves as expected with the negative or unwanted user inputs. The purpose of negative testing is to ensure that the software application does not crash and remains stable with invalid data inputs.
Tools for functional Testing
JUnit is the most popular and widely used testing framework for java.
- The integration of this dependency will allow us to write test cases cleaner and flexibly.
Truth is owned and maintained by the Guava team. It is used in the majority of the tests in Google’s own codebase.
- faster to type, especially with autocompletion.
- easier to read.
- less boilerplate code.
Let’s start with a simple example of a unit test to test email and password fields validations.
Create a ValidatorUtilsTest.kt file app/src/test/java inside your android studio project.
- To test any function you can annotate that function with @Test .
- Create input data for the functionality that need to be tested as per the requirements.
- Output is determined for the functionality under test from the requirements specification.
- assertThat is used for assertion, it is used to make sure that your result is true or false
- Test cases are passed then you can write an actual function for your functionality.
Mockito is a popular open-source framework for mocking objects in software tests. Using Mockito greatly simplifies the development of tests for classes with external dependencies.
A mock object is a dummy implementation for an interface or a class.
Creating mock objects with the Mockito API
- Using the static mock() method.
- Using the @Mockannotation.
- Create a mock object with the use of @Mock or mock()
The when(….).thenReturn(….) method chain is used to specify a return value for a method call with pre-defined parameters.
Let’s start with how to write test cases for firebase functions.
Источник
Тестирование Android приложений
Введение
Я уверен, что современных программистов не нужно убеждать использовать юнит тесты. И если при разработке приложений под android, модули не связанные с ним, мы можем протестировать с помощью знакомого всем JUnit’а (не всегда без костылей правда), то как тестировать user interface и использующие его классы? В этом нам помогут инструменты фреймворка android.test.
В данной статье мы напишем небольшое android приложение и протестируем его. Для работы нам будут нужны установленные jdk, android sdk, Eclipse и ADT плагин.
Часть первая. SpeedConverter.
Наше примитивное приложение будет переводить «километры в час» в «метры в секунду» и наоборот, а также выдавать сообщение Error!, если нужное значение не удается вычислить. Пользователь будет вводить данные о скорости в любой EditText и в другом получать результат. Более подробно на нем останавливаться не будем.
XML layout формы:
xml version =«1.0» encoding =«utf-8» ? >
LinearLayout xmlns:android =«schemas.android.com/apk/res/android»
android:orientation =«vertical»
android:layout_width =«fill_parent»
android:layout_height =«fill_parent»
android:padding =«12dp» >
TextView
android:id =»@+id/textKmPerHour»
android:text =»@string/kmh»
android:layout_width =«wrap_content»
android:layout_height =«wrap_content»/>
EditText
android:id =»@+id/editKmPerHour»
android:layout_height =«wrap_content»
android:layout_width =«match_parent»
android:inputType =«numberDecimal»
android:numeric =«decimal»/>
TextView
android:id =»@+id/textMetersPerSec»
android:text =»@string/ms»
android:layout_width =«wrap_content»
android:layout_height =«wrap_content»
android:paddingTop =«4dp»/>
EditText
android:id =»@+id/editMetersPerSec»
android:layout_height =«wrap_content»
android:layout_width =«match_parent»
android:inputType =«numberDecimal»
android:numeric =«decimal»/>
LinearLayout >* This source code was highlighted with Source Code Highlighter .
Далее устанавливаем listener для Kilometers per hour EditText’а и при наступлении события вычисляем скорость. Нюанс, что onKey() не наступает при активной software клавиатуре мы учтем позже в тестах. Второй EditText работает по аналогии.
// setup listener for Kilometers per hour EditText
editKmPerHour.setOnKeyListener( new OnKeyListener() <
public boolean onKey(View v, int keyCode, KeyEvent event ) <
if ( event .getAction() == KeyEvent.ACTION_UP) <
try <
double kmPerHour = Double.parseDouble(editKmPerHour
.getText().toString());
double meterPerSec = kmPerHour * 0.2777777777777778;
editMeterPerSec.setText( new Double(meterPerSec)
.toString());
> catch (NumberFormatException e) <
editMeterPerSec.setText(R. string .errorMsg);
Log.d(LOG, «e:» + e);
>
return true ;
>
return false ;
>
>);* This source code was highlighted with Source Code Highlighter .
Теперь перейдем к тестированию.
Часть вторая. SpeedConverterTest.
Android Test Project
В первой части мы создали приложение SpeedConverter. Сейчас для него нам нужно создать новое тестовое приложение. Идем в меню eclipse’a: File -> New -> Projects. в появившемся окне выбираем Android -> Android Test Project, нажимаем Next и видим такое окно:
Зададим следующие значения:
- Test Project Name: SpeedConverterTest
- Test Target: устанавливаем «An existing Android project» и выбираем наше проект SpeedConverter
- Application name и Package name подставятся автоматически
И кликаем Finish.
Создание Test Case класса
В директории src/ нашего проекта мы создадим новый класс New > Class. Назовем его SpeedConverterTest и в качестве SuperClass’а укажем android.test.ActivityInstrumentationTestCase2. Наш диалог будет выглядеть так:
Теперь немного подробней об ActivityInstrumentationTestCase2. Данный класс спроектирован для тестирования activities в android приложении. Он может создавать activity (используя InstrumentationTestCase.launchActivity()), запускать тесты в UI thread и позволяет посылать нам различные mock Intents в нашу activity. В качастве параметра мы должны будем передать SpeedConverter.
Добавим test case конструктор который будет использоваться тестирующим фреймворком. В качестве параметров мы покажем какое android приложение будет тестироваться.
public SpeedConverterTest() <
super( «com.pyjioh» , SpeedConverter. class );
>
Далее, знакомый по JUnit’у метод setUp(), который вызывается перед запуском тестов, будем инициализировать в нем переменные.
@Override
protected void setUp() throws Exception <
// TODO Auto-generated method stub
super.setUp();
activity = getActivity();
editKmPerHour = (EditText) activity
.findViewById(com.pyjioh.R.id.editKmPerHour);
editMeterPerSec = (EditText) activity
.findViewById(com.pyjioh.R.id.editMetersPerSec);
>
Начинаем добавлять тесты, они будут простыми дабы показать как взаимодействовать с UI, первый будет проверять — создалась и запустилась ли наша SpeedConverter activity, а также имеем ли мы доступ к нашим контролам.
public void testControlsCreated() <
assertNotNull(activity);
assertNotNull(editKmPerHour);
assertNotNull(editMeterPerSec);
>
Используя метод assertOnScreen() из ViewAsserts проверяем видны ли наши контролы.
public void testControlsVisible() <
ViewAsserts.assertOnScreen(editKmPerHour.getRootView(), editMeterPerSec);
ViewAsserts.assertOnScreen(editMeterPerSec.getRootView(), editKmPerHour);
>
Запускается ли приложение с пустыми EditText’ми.
public void testStartingEmpty() <
assertEquals( «editKmPerHour is not empty» , «» , editKmPerHour.getText()
.toString());
assertEquals( «editMeterPerSec is not empty» , «» , editMeterPerSec
.getText().toString());
>
Теперь добавим тест, проверяющий правильность перевода км/с в м/с. В нем мы используем TouchUtils.tapView(..) который симулирует касание по нужному нам контролу, а KeyEvent.KEYCODE_BACK убирает software клавиатуру. Метод void testConvertMsToKmh() выглядит аналогично.
public void testConvertKmhToMs() <
TouchUtils.tapView( this , editKmPerHour);
sendKeys(KeyEvent.KEYCODE_BACK, KeyEvent.KEYCODE_1, KeyEvent.KEYCODE_0,
KeyEvent.KEYCODE_0);
double meterPerSec;
try <
meterPerSec = Double.parseDouble(editMeterPerSec.getText()
.toString());
> catch (Exception e) <
meterPerSec = -1;
>
assertTrue( «100 km/h is not 27.778 m/s» , meterPerSec > 27.7
&& meterPerSec
Последний тест проверяет — получаем ли мы сообщение об ошибке.
public void testGetError() <
TouchUtils.tapView( this , editKmPerHour);
sendKeys(KeyEvent.KEYCODE_1, KeyEvent.KEYCODE_DEL);
assertEquals( «Must be Error!» ,
activity.getString(com.pyjioh.R. string .errorMsg),
editMeterPerSec.getText().toString());
>
Запустим наше тестовое приложение: Run As > Android JUnit Test. На видео ниже показано как это будет выглядеть.
Таким образом, мы протестировали функционал нашего несерьезного приложения.
Источник