Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
180 views
in Technique[技术] by (71.8m points)

.net core - Mock methods of a class not given by DI

I have a class I am trying to test. The class constructor has a class that is injected and another class that is initialized in the constructor. The second class comes from an external source.

public class MyClass
{
    private readonly ILogger<MyClass> _logger;
    private readonly MavlinkParse _mavlink;

    public MyClass(ILogger<MyClass> logger)
    {
        _logger = logger;
        _mavlink = new MavlinkParse();
    }
}

Later I have a method where I call the _mavlink methods based on a condition. I want to somehow mock the methods, or better yet just "spy" on them and know which was called.

The method:

public SomeMethod(input)
{
    if(cond)
        return _mavlink.method1(lots of params);
    return _mavlink.method2(lots of params);
}

I know how to mock the logger using xunit and moq. What I am stuck on is how to test SomeMethod().

I come from the angular world, where I could easily solve this issue with a spy, and expect(method1Spy).toHaveBeenCalled() would be perfect. I would also be able to settle for the idea of having method1() return a hard-coded value, ignoring params, and check that that came through

How can I achieve this effect in c# dotnet core using xunit and moq?

question from:https://stackoverflow.com/questions/66048464/mock-methods-of-a-class-not-given-by-di

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...