Skip to content

Commit c7fe67e

Browse files
GRAILS-6377 - improve the way the addTo method is being mocked. In particular, when a class has a hasMany that refers to a collection of its own type, don't treat the relationship as a many-to-many.
1 parent eb8d5bb commit c7fe67e

File tree

2 files changed

+29
-1
lines changed

2 files changed

+29
-1
lines changed

src/java/grails/test/MockUtils.groovy

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -825,7 +825,7 @@ class MockUtils {
825825
if (otherHasMany) {
826826
// many-to-many
827827
otherHasMany.each { String otherCollectionName, Class otherCollectionType ->
828-
if (clazz.isAssignableFrom(otherCollectionType)) {
828+
if (clazz.isAssignableFrom(otherCollectionType) && clazz != otherCollectionType) {
829829
if (arg."$otherCollectionName" == null) {
830830
arg."$otherCollectionName" = GrailsClassUtils.createConcreteCollection(otherCollectionType)
831831
}

src/test/grails/test/MockUtilsTests.groovy

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -503,6 +503,21 @@ class MockUtilsTests extends GroovyTestCase {
503503
assertSame aliceDoeUS, relation.testDomain
504504
}
505505
}
506+
507+
void testAddToWithRelationshipToSameClass() {
508+
def c1 = new Company(name: 'c1')
509+
def c2 = new Company(name: 'c2')
510+
def c3 = new Company(name: 'c3')
511+
512+
MockUtils.mockDomain (Company, [c1, c2, c3])
513+
c1.addToSubsidiaries(c2)
514+
c2.addToSubsidiaries(c3)
515+
assertEquals 'c1 had wrong number of subsidiaries', 1, c1.subsidiaries?.size()
516+
assertTrue 'c1 had wrong subsidiary', c1.subsidiaries.contains(c2)
517+
518+
assertEquals 'c2 had wrong number of subsidiaries', 1, c2.subsidiaries?.size()
519+
assertTrue 'c2 had wrong subsidiary', c2.subsidiaries.contains(c3)
520+
}
506521

507522
/**
508523
* Tests the dynamically added <code>removeFrom*()</code> method.
@@ -1444,6 +1459,19 @@ class TestController {
14441459
}
14451460
}
14461461

1462+
class Company {
1463+
Long id
1464+
Long version
1465+
String name
1466+
static hasMany = [subsidiaries: Company]
1467+
static belongsTo = [parentCompany: Company]
1468+
Set subsidiaries
1469+
1470+
String toString() {
1471+
name
1472+
}
1473+
}
1474+
14471475
/**
14481476
* Domain class used to test MockUtils.
14491477
*/

0 commit comments

Comments
 (0)