package com.activeandroid.test; import com.activeandroid.Model; import com.activeandroid.annotation.Column; import com.activeandroid.annotation.Table; import java.util.List; import static junit.framework.Assert.assertEquals; /** * Tests model relationships. */ public class ModelRelationshipTest extends ActiveAndroidTestCase { /** * Correct use of the one-to-many relatinship support in AA. */ public void testOneToMany() { One one = new One(); one.save(); Many many1 = new Many(); Many many2 = new Many(); many1.setOne(one); many2.setOne(one); many1.save(); many2.save(); List manyList = one.many(); assertEquals(2, manyList.size()); } /** * Invalid use - collection change does not reflect back! */ public void testOneToManyInvalidUseCollection() { One one = new One(); one.save(); Many many = new Many(); many.save(); // this will not work the way you expect!! // result of many() is a list returned from a query, // changes to it are not reflected back to the database! one.many().add(many); one.save(); List manyList = one.many(); //now you could expect the Many instance to be in the collection, but in fact, it's empty //as the collection is just a one-way trip. assertEquals(1, manyList.size()); } /** * Invalid use - querying for related models on an unsaved model does not * make sense. */ public void testOneToManyInvalidUnsaved() { One one = new One(); //one.save(); //if you uncomment this, the test will pass Many many1 = new Many(); Many many2 = new Many(); many1.setOne(one); many2.setOne(one); many1.save(); many2.save(); one.many(); //there will be a NPE here, because one.getId() returns null } @Table(name = "One") public static class One extends Model { public List many() { return getMany(Many.class, "OneFK"); } } @Table(name = "Many") public static class Many extends Model { @Column(name = "OneFK") private One one; public One getOne() { return one; } public void setOne(One one) { this.one = one; } } }