0

Hi I'm developing a Play 2 app.

By convention there are views, models and controllers. Views call controllers (by routes) and controllers call models. Models are filled with data by database calls initiated by the given finder.

Well, now I created my first controller test. The controller method I want to test is a method that calls a user model itself (User user = User.findByName("someName");). So this means this method is coupled to this model class. To test this method I have to set up an in-memory database with testdata which is called by the finder of the user model during the test. But this makes my unit test to an integration test. Because every controller method is static I can't inject a mock of the model. Is this the right way Play recommends? Or is there a way to substitute models by mocks during testing.

I thought about accessing models by a ModelProvider or so that is able to substitute models by mocks in the Tests.

What do you think? Or is this overkill?

Thanx Nick

nick78
  • 251
  • 3
  • 19

1 Answers1

1

I also found this difficult. What I did eventually is to use a factory to get the model class, and injected a mock class instead of the original one.

If you replace the model with a simple in memory database, it is still considered a unit test. This could also do the trick for you and shouldn't be very difficult to set up.

One thing that was difficult for me to find, is how to set up a different conf file for testing. This code snippet does the trick. make sure you have a test.conf file with the mock in memory database configured there.

protected Configuration additionalConfigurations;

protected AbstractTest()
{
    Config additionalConfig = ConfigFactory.parseFile(new File("conf/test.conf"));
    additionalConfigurations = new Configuration(additionalConfig);
    start(fakeApplication(additionalConfigurations.asMap(),fakeGlobal()));
}
Omri374
  • 2,555
  • 3
  • 26
  • 40