apache / apache/grails-core

Best Practice for mocking Tenants API in unit tests for multi tenant applications

Open
#14,632 1 comment 0 reactions 0 assignees View on GitHub
relates-to: gorm
Dominant language
Groovy
Stars
2.9k
Forks
975
Avg merge
1d 22h
Merged PRs (30d)
92

Description

Is there an easy mechanism for mocking the Tenants API in unit tests for a multi tenant application?

With my application configured for DISCRIMINATOR mode multi tenancy, I get an error without doing metaprogramming on the Tenants class. In FooSpec below, if I don't specify the:

`Tenants.metaClass.static.currentId = { "test" }`

in the setup method, I receive the error:

```
Datastore implementation does not support multi-tenancy
java.lang.UnsupportedOperationException: Datastore implementation does not support multi-tenancy
at grails.gorm.multitenancy.Tenants.currentId(Tenants.groovy:62)
at multitenantsample.Foo.(Foo.groovy:10)
at multitenantsample.FooSpec.test save foo(FooSpec.groovy:20)
```

This is reasonably straightforward for mocking the currentId() method, but methods like withCurrent, eachTenant, or withId seem like they will be fairly complex to mock.

Also, is there a way to get the String tenantId = Tenants.currentId() functionality automatically, so that the tenantId defaults to the currentId whenever I create a new Foo?

Foo DO:
```
class Foo implements MultiTenant {

String tenantId = Tenants.currentId()
String name

static constraints = {
name unique: true
}
}
```

FooSpec:
```
@TestMixin(GrailsUnitTestMixin)
@Mock([Foo])
class FooSpec extends Specification {

def setup() {
Tenants.metaClass.static.currentId = { "test" }
}

void "test save foo"() {
given:
new Foo(name: 'foo1').save(flush: true, failOnError: true)

expect:
Foo.count == 1
}
}
```

Contributor guide

Open the contributing guide

Research direction

Start with grails.gorm.multitenancy.Tenants.groovy and the FooSpec setup shown in the issue, then trace Foo.groovy where tenantId calls Tenants.currentId(). Compare the available unit-test support for currentId, withCurrent, eachTenant, and withId. Done means the supported testing approach and default tenantId behavior are decided and documented, or the required change is clearly scoped.

Written by the indexing model from the issue text.

Assessment

Tech stack
groovy
Domain
backend, testing
Issue type
Documentation
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
20/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.