Condividi tramite


Testare l'organizzazione e i metadati in MSTest

MSTest fornisce attributi per organizzare i test, aggiungere metadati e collegare i test ai sistemi di rilevamento del lavoro. Questi attributi consentono di filtrare, ordinare e gestire i test in modo efficace in gruppi di test di grandi dimensioni.

Informazioni generali

Gli attributi dei metadati vengono visualizzati nella finestra Proprietà di Visual Studio per i metodi di test. Ti aiutano:

  • Organizzare i test: raggruppare i test per categoria, priorità o proprietario.
  • Filtrare le esecuzioni dei test: eseguire subset specifici di test in base ai metadati.
  • Tenere traccia della copertura dei test: collegare i test agli elementi di lavoro e ai requisiti.
  • Generare report: includere i metadati nei report di test e nei dashboard.

Categorizzazione dei test

TestCategoryAttribute

Raggruppa i TestCategoryAttribute test in categorie per il filtro e l'organizzazione. È possibile applicare questo attributo a livello di metodo, classe o assembly e le categorie vengono combinate se applicate a più livelli.

Categorie a livello di metodo

Applicare le categorie direttamente ai metodi di test per un controllo con granularità fine:

[TestClass]
public class OrderTests
{
    [TestMethod]
    [TestCategory("Integration")]
    public void CreateOrder_SavesOrderToDatabase()
    {
        // Integration test
    }

    [TestMethod]
    [TestCategory("Unit")]
    public void CalculateTotal_ReturnsSumOfItems()
    {
        // Unit test
    }

    [TestMethod]
    [TestCategory("Integration")]
    [TestCategory("Slow")]
    public void ProcessLargeOrder_CompletesSuccessfully()
    {
        // Multiple categories allowed
    }
}

Categorie a livello di classe

Applicare una categoria a una classe di test per assegnare tale categoria a tutti i metodi di test all'interno della classe :

[TestClass]
[TestCategory("Payments")]
public class PaymentServiceTests
{
    [TestMethod]
    public void ProcessPayment_ValidCard_Succeeds()
    {
        // Inherits "Payments" category from class
    }

    [TestMethod]
    [TestCategory("Slow")]
    public void ProcessBatchPayments_LargeVolume_CompletesSuccessfully()
    {
        // Has both "Payments" (from class) and "Slow" (from method) categories
    }
}

Categorie a livello di assembly

Applicare una categoria a livello di assembly per classificare tutti i test nell'intero assembly di test. Questo approccio è utile per distinguere i tipi di test tra progetti:

// In AssemblyInfo.cs or any file in your test project
using Microsoft.VisualStudio.TestTools.UnitTesting;

[assembly: TestCategory("E2E")]

Usare le categorie a livello di assembly per organizzare i progetti di test in base al tipo di test:

Progetto Categoria di assemblaggio Scopo
MyApp.UnitTests Unit Test unitari rapidi e isolati
MyApp.IntegrationTests Integration Test con dipendenze esterne
MyApp.E2ETests E2E Test di scenario completo

Filtrare i test per categoria

Eseguire test per categoria usando il dotnet test comando :

# Run only integration tests
dotnet test --filter TestCategory=Integration

# Run tests in multiple categories
dotnet test --filter "TestCategory=Integration|TestCategory=Unit"

# Exclude slow tests
dotnet test --filter TestCategory!=Slow

In Esplora Test di Visual Studio, usa la casella di ricerca con il prefisso Trait:.

  • Trait:"TestCategory=Integration" - mostra i test di integrazione
  • -Trait:"TestCategory=Slow" - esclude i test lenti

TestPropertyAttribute

TestPropertyAttribute aggiunge metadati chiave-valore personalizzati ai test. Usare questo attributo quando gli attributi predefiniti non soddisfano le proprie esigenze.

[TestClass]
public class CustomMetadataTests
{
    [TestMethod]
    [TestProperty("Feature", "Authentication")]
    [TestProperty("Sprint", "23")]
    [TestProperty("RiskLevel", "High")]
    public void Login_WithValidCredentials_Succeeds()
    {
        // Test with custom properties
    }

    [TestMethod]
    [TestProperty("Feature", "Authorization")]
    [TestProperty("RequirementId", "REQ-AUTH-001")]
    public void AccessAdminPage_RequiresAdminRole()
    {
        // Link to requirements
    }
}

Le proprietà vengono visualizzate nella finestra Proprietà di Visual Studio in Test specifico.

Filtrare in base alle proprietà personalizzate

# Filter by custom property
dotnet test --filter "Feature=Authentication"

Testare la proprietà e la priorità

OwnerAttribute

OwnerAttribute identifica chi è il responsabile di un test.

[TestClass]
public class PaymentTests
{
    [TestMethod]
    [Owner("jsmith")]
    public void ProcessPayment_ChargesCorrectAmount()
    {
        // John Smith owns this test
    }

    [TestMethod]
    [Owner("team-payments")]
    public void RefundPayment_CreditsCustomerAccount()
    {
        // Team responsibility
    }
}

Filtrare i test in base al proprietario:

dotnet test --filter Owner=jsmith

PriorityAttribute

L'importanza relativa del test è indicata da PriorityAttribute. I valori inferiori indicano una priorità più alta.

[TestClass]
public class CriticalPathTests
{
    [TestMethod]
    [Priority(0)]
    public void Login_IsAlwaysAvailable()
    {
        // Highest priority - core functionality
    }

    [TestMethod]
    [Priority(1)]
    public void CreateAccount_WorksCorrectly()
    {
        // High priority
    }

    [TestMethod]
    [Priority(2)]
    public void CustomizeProfile_SavesPreferences()
    {
        // Medium priority
    }
}

Filtra i test per priorità.

# Run only highest priority tests
dotnet test --filter Priority=0

# Run high priority or higher
dotnet test --filter "Priority=0|Priority=1"

DescriptionAttribute

Il DescriptionAttribute fornisce una descrizione in linguaggio umano di ciò che il test verifica.

Avvertimento

Usare Microsoft.VisualStudio.TestTools.UnitTesting.DescriptionAttribute, non System.ComponentModel.DescriptionAttribute. L'analizzatore MSTEST0031 rileva un utilizzo non corretto.

[TestClass]
public class DocumentedTests
{
    [TestMethod]
    [Description("Verifies that orders over $100 receive a 10% discount")]
    public void ApplyDiscount_LargeOrder_Gets10PercentOff()
    {
        // Test implementation
    }

    [TestMethod]
    [Description("Ensures email validation rejects malformed addresses")]
    public void ValidateEmail_InvalidFormat_ReturnsFalse()
    {
        // Test implementation
    }
}

Tracciamento degli elementi di lavoro

WorkItemAttribute

I WorkItemAttribute collegamenti collegano i test agli elementi di lavoro nel sistema di tracciamento, come Azure DevOps.

[TestClass]
public class BugFixTests
{
    [TestMethod]
    [WorkItem(12345)]
    [Description("Regression test for bug #12345")]
    public void DatePicker_LeapYear_HandlesFebruary29()
    {
        // Test that verifies the bug fix
    }

    [TestMethod]
    [WorkItem(67890)]
    [WorkItem(67891)]  // Can link multiple work items
    public void Export_LargeDataset_CompletesWithinTimeout()
    {
        // Test related to multiple work items
    }
}

GitHubWorkItemAttribute

I GitHubWorkItemAttribute colleghi i test ai problemi di GitHub.

[TestClass]
public class GitHubLinkedTests
{
    [TestMethod]
    [GitHubWorkItem("https://github.com/myorg/myrepo/issues/42")]
    public void FeatureX_WorksAsExpected()
    {
        // Test linked to GitHub issue #42
    }

    [TestMethod]
    [GitHubWorkItem("https://github.com/myorg/myrepo/issues/100")]
    [Ignore("Waiting for upstream fix")]
    public void DependentFeature_RequiresUpdate()
    {
        // Ignored test linked to tracking issue
    }
}

Gli attributi degli elementi di lavoro sono particolarmente utili se combinati con Ignore:

[TestMethod]
[Ignore("Known issue, tracked in work item")]
[WorkItem(99999)]
public void KnownIssue_AwaitingFix()
{
    // Provides traceability for why the test is ignored
}

Combinazione di attributi

Combinare più attributi di metadati per un'organizzazione di test completa:

[TestClass]
public class FullyDocumentedTests
{
    [TestMethod]
    [TestCategory("Integration")]
    [TestCategory("API")]
    [Owner("payment-team")]
    [Priority(1)]
    [Description("Verifies that the payment API returns correct error codes for invalid requests")]
    [WorkItem(54321)]
    [TestProperty("Sprint", "24")]
    [TestProperty("Feature", "ErrorHandling")]
    public void PaymentAPI_InvalidRequest_ReturnsAppropriateErrorCode()
    {
        // Well-documented test with full traceability
    }
}

Procedure consigliate

  1. Usare categorie coerenti: stabilire convenzioni di denominazione per le categorie di test nel progetto.

  2. Impostare le priorità in modo strategico: Riservare Priority(0) per i test di percorso critico che devono essere superati per una compilazione valida.

  3. Collegamento agli elementi di lavoro: collegare sempre i test agli elementi di lavoro correlati per la tracciabilità, in particolare i test di regressione dei bug.

  4. Scopo del test del documento: usare Description per i test complessi in cui il nome del metodo non spiega completamente la finalità.

  5. Mantenere aggiornati i metadati: aggiornare i metadati quando l'ambito di test o la proprietà cambia.

  6. Usare le categorie per filtrare: progettare le categorie per supportare le esigenze della pipeline CI/CD, ad esempio "Smoke", "Nightly", "Integration".

Filtro dei test

Filtro della riga di comando

# Filter by category
dotnet test --filter TestCategory=Unit

# Filter by owner
dotnet test --filter Owner=jsmith

# Filter by priority
dotnet test --filter Priority=0

# Combine filters (AND)
dotnet test --filter "TestCategory=Integration&Priority=0"

# Combine filters (OR)
dotnet test --filter "TestCategory=Smoke|TestCategory=Critical"

# Exclude by filter
dotnet test --filter TestCategory!=Slow

# Filter by custom property
dotnet test --filter "Feature=Payments"

Esploratore dei test di Visual Studio

Usare la casella di ricerca in Esplora Test:

  • Trait:"TestCategory=Integration" - filtra per categoria
  • Trait:"Owner=jsmith" - filtrare in base al proprietario
  • Trait:"Priority=0" - filtrare in base alla priorità

Per ulteriori informazioni sul filtro dei test, vedere Esegui unit test selettivi.

Vedere anche