Pular para o conteúdo principal

Spek Example

Introduction

In the world of mobile development, APIs play a crucial role in building robust and scalable applications. Spek API is a popular open-source testing framework for Kotlin and Java, which is used to write unit tests for Android applications. In this article, we will discuss Spek API in Android and how it can be used to write unit tests in Kotlin or Java.

What is Spek API?

Spek API is a testing framework for Kotlin and Java, which allows developers to write expressive and readable tests. It is designed to provide an easy-to-use API for writing unit tests, which can be integrated with other testing frameworks like JUnit and TestNG.

Spek API is built on top of JUnit 5 and provides a fluent and expressive API for writing unit tests. It also supports a wide range of testing scenarios, including parameterized tests, nested tests, and asynchronous tests.

Getting Started with Spek API

To get started with Spek API, you need to add the Spek Gradle plugin to your project and configure it to use the Spek API library. Here's how you can do it:

plugins {
id 'java'
id 'application'
id 'org.jetbrains.kotlin.jvm' version '1.3.72'
id 'org.jetbrains.kotlin.plugin.serialization' version "1.3.72"
id 'org.jetbrains.kotlin.plugin.allopen' version '1.3.72'
id 'com.adarshr.test-logger' version '1.2.0'
id 'org.jetbrains.kotlin.kapt' version '1.3.72'
id 'org.jetbrains.kotlin.plugin.noarg' version '1.3.72'
id 'org.jetbrains.dokka' version '1.4.0-rc-82'
id 'org.jetbrains.kotlin.plugin.parcelize' version '1.3.72'
id 'org.jetbrains.kotlin.plugin.android' version '1.3.72'
id 'org.jetbrains.kotlin.plugin.android.extensions' version '1.3.72'
}

repositories {
google()
mavenCentral()
}

dependencies {
testImplementation "org.spekframework.spek2:spek-dsl-jvm:2.0.8"
testImplementation "org.spekframework.spek2:spek-runner-junit5:2.0.8"
}

Once you have added the Spek Gradle plugin and configured your project to use the Spek API library, you can start writing tests using the Spek API.

Writing Tests with Spek API

Here's an example of how you can write a test using the Spek API:

import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
import kotlin.test.assertEquals

object CalculatorSpec : Spek({
describe("a calculator") {
val calculator = Calculator()

it("should return the sum of two numbers") {
assertEquals(2, calculator.add(1, 1))
}

it("should return the difference of two numbers") {
assertEquals(0, calculator.subtract(1, 1))
}
}
})

In this example, we have defined a test suite for a calculator class. We have defined two tests, one to test the add method and another to test the subtract method. We have also defined an instance of the calculator class outside the tests, which can be reused across the tests.

The Spek API provides a fluent and expressive API for defining tests. We use the describe method to define a test suite and the it method to define individual tests. We have also used the assertEquals method to assert that the results of the operations are as expected.

More Examples

Learn about Kotlin Spek API using this simple example.

Kotlin Spek API

Step 1: Create Project

Start by creating an empty Android Studio project.

Step 2: Dependencies

In your app/build.gradle add the following testImplementation:

    //Spek
testImplementation 'org.jetbrains.spek:spek-api:1.1.2'
testImplementation 'org.jetbrains.spek:spek-junit-platform-engine:1.1.2'
testImplementation 'org.junit.platform:junit-platform-runner:1.0.0-M4'
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.0.0-M4'

Step 3: Design Layout

Design your layout as follows:

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.developers.spekexample.MainActivity">

<EditText
android:id="@+id/edit_text_email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:hint="@string/email_hint_text" />

<Button
android:id="@+id/validate_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text="@string/validate_button" />
</LinearLayout>

Step : Create EmailValidator

EmailValidator.kt

import android.text.Editable
import android.text.TextWatcher
import java.util.regex.Pattern

class EmailValidator : TextWatcher {

private val EMAIL_PATTERN = Pattern.compile(
"[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}" +
"\\@" +
"[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" +
"(" +
"\\." +
"[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25}" +
")+"
)

private var isValid = false

fun isValid(): Boolean {
return isValid
}

fun isValidEmail(email: CharSequence?): Boolean {
return email != null && EMAIL_PATTERN.matcher(email).matches()
}


override fun afterTextChanged(editable: Editable?) {
isValid = isValidEmail(editable)
}

override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

}

override fun onTextChanged(p0: CharSequence?, start: Int, count: Int, after: Int) {

}

}

Step : Write Activity code

First create an extensions class:

Extensions.kt

import android.content.Context
import android.widget.Toast

fun Context.toast(msg: CharSequence, duration: Int) {
Toast.makeText(applicationContext, msg, duration).show()
}

MainActivity.kt

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

private lateinit var emailValidator: EmailValidator

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
emailValidator = EmailValidator()
edit_text_email.addTextChangedListener(emailValidator)
validate_button.setOnClickListener {
if (emailValidator.isValid()) {
toast("Valid Mail", Toast.LENGTH_SHORT)
} else {
toast("Access Denied. Invalid Mail!!", Toast.LENGTH_SHORT)
}
}

}
}

Run

Copy the code or download it in the link below, build and run.

Reference

Here are the reference links:

NumberLink
1.Download Example
2.Follow code author
3.Code: Apache 2.0 License

Conclusion

Spek API is a powerful and easy-to-use testing framework for Kotlin and Java. It provides a fluent and expressive API for writing unit tests, which makes it easy to write readable and maintainable code. If you're looking for a testing framework that can help you write robust and scalable Android applications, Spek API is definitely worth considering.