serenity icon indicating copy to clipboard operation
serenity copied to clipboard

Unit Tests

Open S0raWasTaken opened this issue 2 years ago • 5 comments

I've been wandering for a while in the documentation and didn't find anything about implementing unit tests for a bot. Is that possible? If so, how?

S0raWasTaken avatar May 06 '22 03:05 S0raWasTaken

You could use something like https://github.com/suneettipirneni/discord-mock-server to mock the discord api

jzeuzs avatar May 06 '22 07:05 jzeuzs

You could use something like suneettipirneni/discord-mock-server to mock the discord api

I don't think this has the complete API?

Milo123459 avatar May 08 '22 14:05 Milo123459

You could use something like suneettipirneni/discord-mock-server to mock the discord api

I don't think this has the complete API?

true, could mock the api manually using https://github.com/alexliesenfeld/httpmock

jzeuzs avatar May 09 '22 09:05 jzeuzs

It's probably easier to test bot logic by decoupling it from Discord. So, extract your commands into simple functions without serenity types in them and unit test those. The actual command function would just call into the extracted function with data from the Context and Message, and it would also post the return value of the extracted function to Discord

kangalio avatar Sep 12 '22 08:09 kangalio

I made an example for you

Here's a straightforward math eval command:

https://github.com/kangalioo/serenity/blob/fab45692c89d8a7fc27b2a11f029a22e53250d9d/examples/e05_command_framework/src/main.rs#L615-L644

Then I extracted the inner logic and added unit tests (and shortened the code). Now it looks like this:

https://github.com/kangalioo/serenity/blob/1a6dc0cf90aa0e40741b8f95ea8f62fff984c79c/examples/e05_command_framework/src/main.rs#L615-L655

Hope this helps :) I believe the issue can be closed now, since the question was answered

kangalio avatar Sep 18 '22 05:09 kangalio