Mock a SQL View Result in Integration Test - grails

I'm running an integration test to test the expectation of my service. What I want to do is integrate a domain class that is wired to a SQL Server view.
Obviously, I cannot insert a record (it's a view). I want to do an integration with a mocked view result set.
Is it possible to mock the view result, but still execute the service method integrated?

Why not use a Unit test and use the #Mock annotation for the Domain object?

Related

How can I find out what test type is being executed?

I've written a plugin to do data migrations under mongodb which inserts test data under a test context (like liquibase does) but the test data is interfering with my functional tests.
I was thinking rather than applying the test data during the test context, I could insert when the test type is 'migration' also.
Within Grails, how do I determine the current test type that is executing?
Thanks!
You can try using the variables currentTestPhaseName and currentTestTypeName from the delegate binding (GantBinding). If you are in _Events.groovy you can directly access them from an event closure. If you are inside a GrailsTestTypeSupport there is a member buildBinding.

Need to mock one service method only in an integration test

I am writing grails integration tests which call out to a controller which call a service which calls another service which calls another service.
Controller -> ServiceA.method1() -> ServiceB.method2() -> ServiceC.method3()
the last method in the last service to be called (ServiceC.method3()) makes a call to the outside world (another JVM) and returns a result, which I want to mock out for my integration test. So I am still testing the chain up to and back from that particular service method.
I was reading up on mocking in grails but it seems that it is only possible in unit testing.
Any tips how to progress this one?
Use the metaClass to override a method's functionality. I do this all the time in my integration tests as my way to mock.
So in your test method do something like this (note that the method arg types must match exactly with the real method):
controller.serviceA.serviceB.serviceC.metaClass.method3 = { Args args ->
// do whatever you want here, set flags to indicate method called,
// assert args, declare return types, etc
// return 'mocked' result
}
Make sure in your integration test tear down method you reset the metaClass of this service otherwise all your other int tests will have the same definition:
controller.serviceA.serviceB.serviceC.metaClass = null
I was reading up on mocking in grails but it seems that it is only
possible in unit testing.
That's certainly not true.
You could use all ways of mocking that are available in Groovy in both unit and integration tests.
With mocking using Map coercion, it can be this easy:
controller.serviceA.serviceB.serviceC = [method3: {return 'MockValue'}] as ServiceC

how to mock datasource in grails for Unit testing

I'm using sql in my domain class finder Method and passing datasource as an argument to sql constructor.
Sql sql = new Sql(dataSource)
How to mock datasource in unit tests?
any suggestions around would be appreciated.
If you need to interact with a database then your test should be an integration test and not a unit test.
http://grails.org/doc/latest/guide/testing.html has a little information, or a general google for "unit vs. integration testing"
If you're not using the sql object you are creating, and are just trying to satisfy it's constructor, then passing as map aliased as an the correct class (with appropriate fields and methods) might work. A little example: http://www.groovyexamples.org/2010/05/25/create-a-mock-object-for-an-abstract-class-using-a-map/ Update: Broken link. Site no longer exists.

Grails withCriteria testing

I'd like to test a "withCriteria" closure and am not sure how to go about it. I see how to mock out the withCriteria call, but not test the code within the closure. When running the test that executes the "withCriteria", I keep getting a MissingMethodException, even though the code runs fine under the normal flow of execution. Any ideas?
Thanks!
Steve
I wouldn't go that route. Instead I'd move the query into the domain class as a static finder method and test it directly in an integration test with real data. Then you can easily mock the helper method when it's called in a controller or service test.
class YourDomainClass {
...
static List<YourDomainClass> findFooBar() {
YourDomainClass.withCriteria {
...
}
}
}
Then in a unit test:
def results = [instance1, instance2, instance3]
YourDomainClass.metaClass.static.findFooBar = { -> results }
This way you test that the query works against the in-memory database in an integration test but it's easy to mock it in unit tests.
Further to Burt's answer, check out named queries as described here:
http://blog.springsource.com/2010/05/24/more-grails-1-3-features/
You can then mock the property/method access in your unit tests as described by Burt.
Since nobody mentioned the option to create a DSL to run other DSLs here's a full disclosure of this method. I use it quite often with very good results.
Groovy/Grails testing DSLs
There's no mock implementation for Hibernate criteria at the present time. You'll need to use integration tests. However, Burt's recommendation of making this a static finder method is a good one for code organization. You should also look at named queries, described at http://www.grails.org/1.2+Release+Notes, for a nice syntax for this.

Test-driven development with ASP.NET MVC - where to begin?

I've read a lot about Test-Driven Development (TDD) and I find the principles very compelling, based on personal experience.
At the moment I'm developing a website for a start-up project I'm involved in, and I'd like to try my hand at putting TDD into practice.
So ... I create a blank solution in Visual Studio 2010, add an ASP.NET MVC Website project and a test project.
I also add a class library called 'Domain', for my domain objects, and a test project for that.
Now I'm wondering where to begin. Should I be writing a test before I do anything right? The question is - should I start writing tests for domain objects? If so, what exactly should I be testing for, since the domain objects don't yet exist?
Or should I be starting with the Website project and writing tests for that? If so, what should I write a test for? The Home controller / Index action?
I typically start by collecting a set of stories for the application I'm going to develop. From that I generate a domain model, usually on "paper". I organize the stories that I'm going to implement and start creating the domain model in the DB for the first set of stories.
Once I have the initial DB, then I use an ORM, in my case, LINQ to SQL, to map the DB tables onto a set of initial classes. I don't typically unit test generated code so this gives me a fair amount of code as a base to start with. I then create a stub method, which throws a not implemented exception, to implement one feature of the first domain class I'm working with. Typically, I start with validation logic. Once you have your stub method, then you can use the VS right click menus to create one or more unit tests for that method. Then you're on your way.
Once I've finished with the domain objects for the first story, I then start working with the MVC aspects. First, I'll create the view models for the first view. These are typically just an empty container class as this point. Then I'll create the view and strongly type it to the view model. I'll start fleshing out the view, adding properties to the view model as needed by the view. Note that since the view model is simply a container there aren't typically unit tests associated with it. It will however be used in subsequent controller tests.
Once the view is complete (or at least my initial concept is complete), I then create the stub controller action or actions for it, again the stub method simply throws a not implemented exception. This is enough to get it to compile and let me use the tools to create unit tests for it. I proceed as needed to test the method(s) and ensure that it acts appropriately to the given inputs and produces an appropriate view model. If the method can produce multiple view models, i.e., render multiple views I may iterate over the process of creating view models/views/controller code until the story or stories are complete.
Repeat as necessary until your set of stories are implemented, refactoring along the way.
Writing unit tests before even declaring the class you are testing seems a little extreme in a static languages such as C#. So you start by declaring your domain classes, throw a few interfaces that define operations you will perform on these domain objects and then you add a class that will implement an interface, leaving methods just throw NotImplementedException. At that moment you could write a unit test for this class, as all the types are known. You run the test which will fail, then you implement the method and run the test again - it will pass. Then you could refactor and optimize your implementation, your unit test should still pass.
Once you have a nice domain model and data access layer you could move to the web project where you create controllers, using the interfaces you previously defined (by making a constructor that takes this interface). You write a unit test for this controller by replacing the interface with a mock object, so that you can test the controller actions in isolation from your data access code.
And most importantly: don't be afraid to add classes and interfaces. I've seen people write huge methods that perform multiple things at the same time and which are difficult to test. Try isolating different tasks into methods that you could easily write specifications for: what output you expect for the different possible inputs.
For a long answer you should take small steps like this.
1)-First write a failing test
[Test]
public void AddSameTag()
{
UserMovie userMovie = new UserMovie();
userMovie.AddTag("action", "dts", "dts");
Assert.AreEqual(2, userMovie.Tags.Count);
}
2)- Write simplest code to pass the test.
public virtual void AddTag(params string[] tags)
{
foreach (var text in tags)
{
Tag tag =new Tag(text.Trim());
if (!movieTags.Contains(tag))
movieTags.Add(tag);
}
}
3)- Refactor
.
For ASP.NET MVC and TDD starter you can ignore Controller Test and focus on Domain by TDD.
You can look at ASP.NET MVC 1.0 Test Driven Development

Resources