dotnet / dotnet/command-line-api

Getting a reference to the InvocationContext

Open
#1,312 0 comments 0 reactions 0 assignees View on GitHub
Area-Hosting and DI
Dominant language
C#
Stars
3.7k
Forks
428
PR merge metrics
No merged PRs in 30d

Description

How do I obtain the InvocationContext after the `Invoke` has completed? Main use case is for unit testing and examining the `InvocationResult`.

The current workaround below, but this is dirty.

```
public class Program
{
internal InvocationContext InvocationContext { get; private set; }

public static async Task Main(string[] args)
{
var _ = GetCommandLineBuilder()
.UseHost(_ => Host.CreateDefaultBuilder(),
host =>
{
InvocationContext = host.GetInvocationContext();
```

and the unit tests like

```
[Test]
public async Task Cli_NoCommand_ParseErrorResult()
{
var args = "";

var p = new Program();
await p.Main(args.Split(' '));

Assert.IsInstanceOf(p.InvocationContext.InvocationResult);
Assert.AreEqual(1, p.InvocationContext.ParseResult.Errors.Count(pe => pe.Message == "Required command was not provided."));
}
```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.