1

I have a method inside my Controller that I want to unit test using Spec2.

object MyController extends Controller with MyAuth {
  def article(id: String) = {
    authenticate {
      ......
    }
  }
}

authenticate is defined in MyAuth. This function gets the token if available or authenticates and gets the token. I want to mock authenticate while unit testing article. I am not sure how to proceed with this. Any pointers will be helpful.

UPDATE: My approach so far. I saw this question and overrode authenticate method in MyAuth trait.

trait MyAuthMock {
  this: MyAuth =>

  override def authenticate ....
}

I also changed MyController to have class and companion object. Then in my test I used the controller as follows

new MyController with MyAuthMock
Community
  • 1
  • 1
Prasanna
  • 3,703
  • 9
  • 46
  • 74

1 Answers1

1

You can refactor your code a little bit to make it easier to test. For example:

class MyController extends Controller {

  def authenticate(...) // abstract method

  def article(id: String) = {
    authenticate {
        ......
    }
  }    
}

object MyController extends MyController with RealAuth

In your test class you would do something like:

val myTestController = new MyController with FakeAuth

Where FakeAuth is a mock.

  • I updated the question with the approach I went with. I am not sure what is the better approach here, yours or mine?. – Prasanna Oct 25 '13 at 23:13