Fluent Nhibernate System.ApplicationException : For property 'Id' expected '1' of type 'System.Int32' but got '2' of type 'System.Int32'

丶灬走出姿态 提交于 2019-12-12 04:26:31

问题


Hi I am writing unit tests for fluent Nhibernate, when I run the test in isloation it passes, but when I run multiple tests. or run the test more than once it starts failing with the message below System.ApplicationException : For property 'Id' expected '1' of type 'System.Int32' but got '2' of type 'System.Int32'

[TextFixture] public void Can_Correctly_Map_Entity() {

        new PersistenceSpecification<UserProfile>(Session)
            .CheckProperty(c => c.Id, 1)
            .CheckProperty(c => c.UserName, "user")
            .CheckProperty(c => c.Address1, "Address1")
            .CheckProperty(c => c.Address2, "Address2")

}


回答1:


I'd suggest testing your mappings using an in-memory database so that you can isolate these tests the mappings only. If you use an in-memory database, you can place the FluentConfiguration in the [TestInitialize] (MSTest) or [SetUp] (NUnit) method, and the db will be created from scratch (in memory) each time. Here's an example:

[TestInitialize]  
public void PersistenceSpecificationTest()  
{  
    var cfg = Fluently.Configure()  
        .Database(SQLiteConfiguration.Standard.InMemory().UseReflectionOptimizer())  
        .Mappings(m => m.FluentMappings.AddFromAssemblyOf<UserProfile>())  
        .BuildConfiguration();  

    _session = cfg.BuildSessionFactory().OpenSession();  
    new SchemaExport(cfg).Execute(false, true, false, _session.Connection, null);  
}  

Then your test should work fine each time you run:

[TestMethod] 
public void CanMapUserProfile() 
{ 
    new PersistenceSpecification<UserProfile>(_session)     
        .CheckProperty(c => c.Id, 1)     
        .CheckProperty(c => c.UserName, "user")     
        .CheckProperty(c => c.Address1, "Address1")     
        .CheckProperty(c => c.Address2, "Address2")  
} 

You'll need to use SQLite in this scenario, along with the System.Data.SQLite DLL, which you can find here: http://sqlite.phxsoftware.com/

Hope that helps.




回答2:


The Id property is an database identity so it is incremented with each insert to the table. Some other test is also inserting a UserProfile so the identity value is incremented to 2 for this insert. I would just verify that the Id property does not equal 0, assuming that's its default value.



来源:https://stackoverflow.com/questions/3188311/fluent-nhibernate-system-applicationexception-for-property-id-expected-1-o

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!