81 lines
2.0 KiB
C#
81 lines
2.0 KiB
C#
using Heimdall.Domain.Primitives;
|
|||
|
|
using Shouldly;
|
||
|
|
|
||
|
|
namespace Heimdall.Domain.Tests.Primitives;
|
||
|
|
|
||
|
|
public class EntityTests
|
||
|
|
{
|
||
|
|
private sealed class TestEntity : Entity<Guid>
|
||
|
|
{
|
||
|
|
public TestEntity(Guid id) : base(id) { }
|
||
|
|
private TestEntity() { } // EF Core
|
||
|
|
}
|
||
|
|
|
||
|
|
private sealed class OtherEntity : Entity<Guid>
|
||
|
|
{
|
||
|
|
public OtherEntity(Guid id) : base(id) { }
|
||
|
|
private OtherEntity() { }
|
||
|
|
}
|
||
|
|
|
||
|
|
[Fact]
|
||
|
|
public void Same_id_entities_should_be_equal()
|
||
|
|
{
|
||
|
|
var id = Guid.NewGuid();
|
||
|
|
var e1 = new TestEntity(id);
|
||
|
|
var e2 = new TestEntity(id);
|
||
|
|
|
||
|
|
e1.Equals(e2).ShouldBeTrue();
|
||
|
|
(e1 == e2).ShouldBeTrue();
|
||
|
|
}
|
||
|
|
|
||
|
|
[Fact]
|
||
|
|
public void Different_id_entities_should_not_be_equal()
|
||
|
|
{
|
||
|
|
var e1 = new TestEntity(Guid.NewGuid());
|
||
|
|
var e2 = new TestEntity(Guid.NewGuid());
|
||
|
|
|
||
|
|
e1.Equals(e2).ShouldBeFalse();
|
||
|
|
(e1 != e2).ShouldBeTrue();
|
||
|
|
}
|
||
|
|
|
||
|
|
[Fact]
|
||
|
|
public void Same_id_should_have_same_hash_code()
|
||
|
|
{
|
||
|
|
var id = Guid.NewGuid();
|
||
|
|
var e1 = new TestEntity(id);
|
||
|
|
var e2 = new TestEntity(id);
|
||
|
|
|
||
|
|
e1.GetHashCode().ShouldBe(e2.GetHashCode());
|
||
|
|
}
|
||
|
|
|
||
|
|
[Fact]
|
||
|
|
public void Different_entity_types_with_same_id_should_be_equal_by_id()
|
||
|
|
{
|
||
|
|
// DDD convention: entity equality is based on ID alone, not type
|
||
|
|
var id = Guid.NewGuid();
|
||
|
|
var testEntity = new TestEntity(id);
|
||
|
|
var otherEntity = new OtherEntity(id);
|
||
|
|
|
||
|
|
testEntity.Equals(otherEntity).ShouldBeTrue();
|
||
|
|
testEntity.GetHashCode().ShouldBe(otherEntity.GetHashCode());
|
||
|
|
}
|
||
|
|
|
||
|
|
[Fact]
|
||
|
|
public void Entity_should_not_be_equal_to_null()
|
||
|
|
{
|
||
|
|
var entity = new TestEntity(Guid.NewGuid());
|
||
|
|
|
||
|
|
entity.Equals(null).ShouldBeFalse();
|
||
|
|
(entity == null!).ShouldBeFalse();
|
||
|
|
(null! == entity).ShouldBeFalse();
|
||
|
|
}
|
||
|
|
|
||
|
|
[Fact]
|
||
|
|
public void Two_null_entities_should_be_equal()
|
||
|
|
{
|
||
|
|
TestEntity? e1 = null;
|
||
|
|
TestEntity? e2 = null;
|
||
|
|
|
||
|
|
(e1 == e2).ShouldBeTrue();
|
||
|
|
}
|
||
|
|
}
|