skip to content

In an ASP.NET Core 10 codebase, how do you test DTO mappings so a new Employee column is neither silently dropped nor leaked into a response?

level: middleimportance: should knowfreq 33%

answer

  1. different mappers fail in different ways
  2. positional records break callers at compile time
  3. AssertConfigurationIsValid checks destination members
  4. Mapperly RMG012 and RMG020 as errors
  5. a response-level test for leaked fields

basics

~20 s

Match the safety net to the mapper: compile errors from positional records for hand-written code, AssertConfigurationIsValid in a unit test for AutoMapper, Mapperly's RMG012 and RMG020 raised to errors, plus one response-level test that the JSON contains no salary.

solid answer

~40 s

Mapping fails in two directions: a DTO member nobody fills (silently dropped), or a member mapped that should not exist (leaked). For **hand-written** mapping, a positional `EmployeeDto` record makes every `new EmployeeDto(...)` stop compiling when a member is added, and a unit test maps a fully populated `Employee` and compares the record by value. For **AutoMapper**, a test calls `AssertConfigurationIsValid()`, which fails on destination members with no source; it does not object to a DTO gaining a `Salary` that maps by name. For **Mapperly**, the generator reports `RMG012` (target member without a source) and `RMG020` (source member not mapped) as warnings since 4.0; raise them to errors and ignore `Salary` explicitly with `[MapperIgnoreSource]`. Leaks get a final net: an integration test that calls the endpoint and asserts the JSON has no `salary` member.

code

csharp · 7 lines
csharp
[Mapper]
public static partial class EmployeeMapper
{
    [MapperIgnoreSource(nameof(Employee.Salary))]
    [MapperIgnoreSource(nameof(Employee.BankAccount))]
    public static partial EmployeeSummaryDto ToSummary(this Employee employee);
}

go deeper

for a junior

Know that each DTO mapping needs a test, and that a positional record makes the compiler point at every place a new member must be filled.

for a middle

Explain the dropped versus leaked directions and which tool catches which: AssertConfigurationIsValid, Mapperly's RMG012 and RMG020, and value-equality tests.

for a senior

Set up the build and test gates: diagnostics as errors, explicit MapperIgnoreSource decisions, and an allow-list test on serialized responses for sensitive resources.

for a principal

Decide which failures the team catches at build, test or review time, and make the cheapest reliable gate mandatory across services.

## Two failure directions A mapping from `Employee` to `EmployeeDto` can go wrong in two ways, and each needs its own check: - **Dropped:** the DTO gains `HireDate`, nothing fills it, and clients receive the default value. No exception, no log. - **Leaked:** someone adds `Salary` to the DTO "for the payroll screen" and every endpoint using that DTO now returns salaries. Name-based mappers make this a one-line change. Which failure you can catch where depends on how the mapping is written. ## Hand-written mapping With a positional record — `public sealed record EmployeeDto(int Id, string FullName, string Email, string Department);` — the constructor is the mapping's checklist: 1. Adding `DateOnly HireDate` to the record breaks every `new EmployeeDto(...)` call at **compile time**, so nothing can be dropped silently. 2. A unit test builds a fully populated `Employee` (every property non-default) and asserts the mapped record equals an expected record; records compare by value, so one `Assert.Equal` covers every member. 3. Leaks need a human to write `e.Salary` into the constructor, which shows up in review as an obvious diff. Object-initializer DTOs with settable properties lose point 1: a new property compiles and stays unset. That is a reason to prefer positional records or `required` members for responses. ## AutoMapper AutoMapper builds maps at runtime by convention, so the checks are runtime checks run from a test: ```csharp [Fact] public void Mapping_configuration_is_valid() { var config = new MapperConfiguration( cfg => cfg.AddProfile<EmployeeProfile>(), NullLoggerFactory.Instance); config.AssertConfigurationIsValid(); } ``` - `CreateMap` validates against the **destination** member list by default, so `AssertConfigurationIsValid()` throws when a DTO member has no matching source — the dropped direction. - It says nothing about source members left unmapped, and a new `EmployeeDto.Salary` **does** have a matching source by name, so the leaked direction passes this test. - Since 15.0 the `MapperConfiguration` constructor takes an `ILoggerFactory`; `NullLoggerFactory.Instance` keeps the test quiet. ## Mapperly Mapperly is a source generator, so its checks happen at **build time** as Roslyn diagnostics: | Diagnostic | Meaning | Default severity since 4.0 | |---|---|---| | `RMG012` | A target member has no source member — dropped | Warning | | `RMG020` | A source member is not mapped to any target member | Warning | Raise both to errors, for example `dotnet_diagnostic.RMG020.severity = error` in `.editorconfig` or `<WarningsAsErrors>RMG012;RMG020</WarningsAsErrors>` in the project file. Because the default `RequiredMappingStrategy` is `Both`, a new `Employee.Salary` column now fails the build until someone writes `[MapperIgnoreSource(nameof(Employee.Salary))]` on the mapping method — a deliberate, reviewable decision for every new column. Setting `EmitCompilerGeneratedFiles` lets reviewers read the generated mapping code. ## The response-level net None of the above notices that a correctly mapped DTO is the wrong DTO for an endpoint. One integration test per sensitive resource closes that gap: host the app in memory, call `GET /employees/{id}` with an ordinary user, parse the JSON and assert there is no `salary`, `bankAccount` or `nationalId` member. It catches leaks whatever the mapper, including an endpoint that returns the entity by accident. Prefer an **allow-list** assertion — the set of property names equals the documented set — over a growing deny-list of forbidden names, so a new field fails the test until it is approved. ## Putting it together - Hand-written: positional records plus one value-equality unit test per mapping. - AutoMapper: `AssertConfigurationIsValid()` in the test suite, plus a review rule for DTO changes. - Mapperly: diagnostics as errors and explicit ignores. - All: an allow-list test on the serialized response of each endpoint that serves sensitive entities.

  • Why does AutoMapper's AssertConfigurationIsValid pass after someone adds Salary to EmployeeDto?
    By default maps validate the destination member list: every DTO member must have a source. `EmployeeDto.Salary` finds `Employee.Salary` by name, so the configuration is valid and the value is mapped. The test protects against dropped members, not leaked ones; a response-level allow-list test or review rule has to cover that direction.
  • What does RMG020 force a team to do when a new column lands on Employee?
    With RMG020 as an error and the default `RequiredMappingStrategy.Both`, the generator reports the new source member as unmapped and the build fails. Someone must either add a target member or write `[MapperIgnoreSource(nameof(Employee.NewColumn))]`, so every new column gets an explicit decision in the diff.

  • AssertConfigurationIsValid would catch a Salary property added to the DTO
  • Mapperly's unmapped-member diagnostics are errors by default
  • Settable-property DTOs catch new members at compile time like positional records
  • If every mapping unit test passes, no endpoint can leak a column
  • A deny-list test of forbidden JSON names is as safe as an allow-list