Unit Test Models - Recommendations

I have a project that several people are working on. I built unit tests for our project. (I know that they should have been there from day one, but I joined after the project was launched.)

We have many models with many properties. I was wondering if you let me know that I am creating unit tests to test these models, are being created correctly and that the properties are set?

+4
source share
3 answers

I would not test that they load correctly for the ORM structure. However, I would add tests if they have some kind of logic, for example:

private IList<User> _allUsers; public IEnumerable<User> GetActiveUser { get { return _allUsers.Where(u => u.IsActive); } 

This may require some tests to make sure that you are only getting active users.

+1
source

Test that the models are correctly stored at any used level of access to the database or data, as well as in any business logic that is built into the models themselves.

I like to use NUnit + Fluent Assertions to compare the model before and after perseverance (for example, creating and saving a model and ensuring that it displays correctly with all values).

Please note that this is not necessarily a strict retention. Perhaps your model is a presentation model and is mapped to a business object using a mapping. I would also experience it. Basically, you want to verify that the model passed through some level or logic correctly, and not tested the model itself (in addition to any business logic built into it, of course). Testing the language or functions of the compiler framework / operation, as it would be when checking the operation of properties, seems to me a waste of time.

Example:

  // arrange var expected = new PersonModel { FirstName = "John", LastName = "Doe", DateOfBirth = DateTime.Now // etc } // act var id = InsertModelAndReturnId(expected); var actual = RetrieveModelById(id); // assert actual.ShouldHave().AllProperties().EqualTo(expected); // ShouldHave is from Fluent Assertions. This line makes sure expected and actual have the same values after being persisted and retrieved 
+1
source

In most cases, you should focus on logic, but not on data. This means that you should not test the state , you should test the behavior .

Perhaps you have some kind of behavior behind your properties. For example, changing the state of one property should affect another property value (but in this case, we will still test the behavior and not indicate the state).

Each unit test should tell a story about the tested class (c). Too many useless unit tests can hide important or important information about your system and actually reduce maintainability, rather than increase it.

Be pragmatic and add tests to the most important parts of your system and first consider the most complex business logic, and they will move to other parts of your system.

0
source

All Articles