-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Description
Description
Introducing a function to assert that no field in a struct is empty.
Proposed solution
Proposed implementation in #1591
Use case
Writing tests where it is important to assert all fields are populated, not just the fields present at the time of creating the test. Often used to avoid tests becoming out-of-date and no longer aligning with their original intention.
An example of this is writing tests that check that all fields in a struct can be stored and then loaded. Consider the test:
// Tests that all fields in entity can be stored and loaded
func TestPersistence(t *testing.T) {
entity := Entity{
// Filled with data
}
s := NewStore()
err := s.Store(entity)
require.NoError(t, err)
result, err := s.Load(entity.ID)
require.NoError(t, err)
assert.Equal(t, entity, result, "result should match the entity stored")
}This test is claiming to check that all fields can be stored and loaded but it not enforcing it. If the entity was not correctly populated initially or if new fields where added to the Entity and the test was not updated then the test would not be aligned with its stated purpose.
In this particular case the assertion could be used as a pre-condition to ensure we always start with all fields containing data
require.NoFieldIsEmpty(t, entity)or as check at the end of test to ensure all fields where populated
assert.NoFieldIsEmpty(t, result)I have found this assertion useful for when using tests that require populated structs including:
- Testing the storing and loading of structs into database or persistence storage.
- Testing the population of structs e.g. writing fakers.
- Testing the marshalling/formatting of structs and unmarshalling/parsing data to structs.