Testing
Tests are an important part of the application. And testing a bot can be extremely simple:
dependencies {
...
testImplementation("io.github.dehuckakpyt.telegrambot:telegram-bot-test:0.11.7a")
}
Example in code with database storing.
Examples:
com/example/myproject/handler/RegistrationHandlerIT.kt
@SpringBootTest
@EnableTelegramBotTest
class RegistrationHandlerIT @Autowired constructor(
private val bot: TelegramBot,
) {
@BeforeEach
fun setUp() {
clearAllMocks()
}
@Test
@DataSet("/datasets/handler/registration/command.json")
@ExpectedDataSet("/datasets/handler/registration/command__expected.json")
fun `register command`() = runTest {
// Arrange
coEvery { bot.sendMessage(1_001, any(), replyMarkup = any()) } returns mockk()
// Act
sendUpdateAsync(resourceAsString("/json/handler/registration/command-update.json"))
// Assert
coVerify(timeout = 3000) {
bot.sendMessage(1_001, "Please, share your phone number.", replyMarkup = isNull(inverse = true))
}
}
}
/json/handler/registration/command-update.json
{
"update_id": 1,
"message": {
"message_id": 2,
"from": {
"id": 1001,
"is_bot": false,
"first_name": "DEHucka_KpyT"
},
"chat": {
"id": 1001,
"type": "private"
},
"date": 1707824482,
"text": "/register"
}
}
com/example/myproject/handler/StartHandlerIT.kt
@SpringBootTest
@EnableTelegramBotTest
class StartCommandIT(
private val bot: TelegramBot,
) : FreeSpec({
beforeEach {
clearAllMocks()
}
"start command" {
// Arrange
coEvery { bot.sendMessage(123, any()) } returns mockk()
// Act
sendUpdate(resourceAsString("/json/handler/start/update.json"))
// Assert
coVerify {
bot.sendMessage(123, "Start command.")
bot.sendMessage(123, "Hello, my name is mock_bot :-)")
}
}
})
/json/handler/start/update.json
{
"update_id": 1,
"message": {
"message_id": 2,
"from": {
"id": 123,
"is_bot": false,
"first_name": "DEHucka_KpyT"
},
"chat": {
"id": 123,
"type": "private"
},
"date": 1707824482,
"text": "/start"
}
}
Last modified: 05 April 2024