-1

I have a AsyncDelegateCommand which takes the parameter of Window, I tried mocking the class but I end with an exception The calling thread must be STA, because many UI components require this.

The DeletegateCommand:

private AsyncDelegateCommand<Window> okCommand;

public AsyncDelegateCommand<Window> OkCommand => this.okCommand ?? (this.okCommand = new AsyncDelegateCommand<Window>(this.OkAsync));

The Method implementaion:

private async Task OkAsync(Window win)
{
   //Logic
}

The way I'm mocking it currently is using :

private Mock<Window> mockWindow;
this.mockWindow = new Mock<Window>();
await this.sut.OkCommand.ExecuteAsync(this.mockWindow.Object);

While debugging the object I can see the object value as an exception this.mock Window.Object' threw an exception of type 'System.Reflection.TargetInvocationException

If it's not possible is there an alternative on how to achieve this?

The Piatre
  • 53
  • 6
  • if you are using xUnit https://www.nuget.org/packages/Xunit.StaFact – Athul Raj Feb 26 '21 at 04:43
  • @AthulRaj I'm using nUnit – The Piatre Feb 26 '21 at 04:50
  • 1
    https://stackoverflow.com/questions/56567075/how-to-run-nunit-test-in-sta-thread – Athul Raj Feb 26 '21 at 04:56
  • also why do you need to mock a window ? i thought we mocked interfaces – Athul Raj Feb 26 '21 at 04:58
  • @AthulRaj How can you verify the methods without mocking it? I'm not able to mock IWindowService Since it's internal. and I guess adding the attribute `[Apartment(ApartmentState.STA)]` over the method does work. – The Piatre Feb 26 '21 at 05:01
  • @AthulRaj mocking `interface`s is certainly common but any `virtual` or `abstract` members of a `class` can also be mocked. I do think mocking `Window` is dubious but not because it's a `class` – Aluan Haddad Feb 26 '21 at 05:30
  • What problem are you trying to solve that you need to pass a UI control to a command - especially one performing an async operation. In MVVM, commands usually live in the ViewModel layer, and the whole purpose of MVVM is clean separation between business logic and the UI. – Peregrine Feb 26 '21 at 05:46
  • @Peregrine how would you suggest separate the Window parameter as the operation is happening in the popped up window – The Piatre Feb 26 '21 at 05:51
  • @ThePiatre The parameter for a command would usually be a data object, not a UI control. – Peregrine Feb 26 '21 at 06:06

1 Answers1

1

I was able to solve the issue by adding an attribute as suggested in the comments [Apartment(ApartmentState.STA)] over my test method

Ex:

[Test]
[Apartment(ApartmentState.STA)]
public async Task TestMethod()
{
    //Logic
}
The Piatre
  • 53
  • 6