Search code examples
testingclojuremail-server

Testing a mail server in clojure tests


I need to test our mail server in a clojure project. To do that I thought I would open a mock up server and send emails using this mock up server and check if they are sent. For that I found for example this server.

To be able to execute

lein test

and have each test tested, I need to run the SMTP server once before each test and once at the end. I can also run the server in a fixture and exit it after each test. Since i am running about 100 tests, it does not make sense to always start and shutdown the server.

My approaches that i thought are the following:

1 - I write a bash script that starts the (mockup) mail server, runs lein test, then shuts down the server. (Here I lose the ease of executing lein test in the IDE)

2- I could have a fixture checking if the server is started and start it if its not. However after the test finished the server will still be running which is not desired.

What is the correct way to solve this problem?

Can I order the tests in clojure such that the last test file shutsdown the mail server ?


Solution

  • One solution is to use the Java GreenMail library. It allows you to start up an SMPT mail server in your JVM, which makes it easy to start, stop and inspect.

    Here are a few snippets from my testing with GreenMail. First you create mail server:

    (def mail-setup (ServerSetup. ServerSetup/PORT_SMTP nil ServerSetup/PROTOCOL_SMTP))
    (def green-mail (GreenMail. mail-setup))
    (.start green-mail)
    ; Now the server listens on localhosts SMPT port for emails. Run your test code
    ; Run the code under test. Then you can receive the emails
    (doseq [m (.getReceivedMessages green-mail)]
       ; Verify the emails etc
       (println "Subject: " (.getSubject m)
                   " TO: " (str/join "," (.getRecipients m Message$RecipientType/TO)))
     )
    ; When done
    (.stop green-mail)
    

    Depending on you your tests you can start and stop it per test. Or might keep a test server running for a whole test suite.

    Check the GreeMail documentation for more details. It supports tons of scenarious.