Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Bug?] Cannot mock class with protected virtual method. #31

Open
voroninp opened this issue Mar 14, 2020 · 1 comment
Open

[Bug?] Cannot mock class with protected virtual method. #31

voroninp opened this issue Mar 14, 2020 · 1 comment

Comments

@voroninp
Copy link

Description

I want to mock behaviour of HttpMessageHandler, but cannot do it because of exceptions thrown by Foq.

Is Strict mode I get NotImplementedException and in Loose mode I get NullReferenceException

Repro steps

open System
open System.Net.Http
open Foq
open System.Threading
open System.Threading.Tasks
open System.Reflection
open System.Linq

[<AbstractClass>]
type TestHandler() = 
    inherit HttpMessageHandler()
    abstract member MockableSendAsync: HttpRequestMessage * CancellationToken -> Task<HttpResponseMessage>
    override this.SendAsync(request, cancellationToken) = this.MockableSendAsync(request, cancellationToken)
    
type TestHandler2() = 
    inherit TestHandler()
    override this.MockableSendAsync(request, token) = Task.FromResult(null)
 
let handler = 
        Mock<TestHandler2>(MockMode.Strict)
            .Setup(fun h -> <@ h.MockableSendAsync(any(), any()) @>)
            .Returns(Task.FromResult(null))
            .Create()

let method = 
        typeof<TestHandler2>
            .GetMethods(BindingFlags.NonPublic ||| BindingFlags.Instance ||| BindingFlags.Public)
            .Single(fun x -> x.Name = "SendAsync")

let p = [|null; box CancellationToken.None|]
let result = method.Invoke(handler, p) :?> Task<HttpResponseMessage>
result.Result

Expected behaviour

It should jus work, I assume =)
I've discovered this does not work with Moq as well.

Related information

  • Operating system: Win 10 x64
  • Foq v. 1.8.0
  • .NET Runtime: .net core 3.1.101
@voroninp
Copy link
Author

Pay attention to this comment

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant