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
112 views
in Technique[技术] by (71.8m points)

c# - How to access the method which is available in the service collection to perform unit tests

I would like to access the finder object inside the unit test class in order to perform test cases, but I am pretty new to the service collections and async programming please help me out with some leads or solution.

// startup class

 public static class Startup
    {
        public static IServiceCollection Configure(IServiceCollection services = null)
        {
            services = services ?? new ServiceCollection();

            services.AddSingleton<ILongestRisingSequenceFinder, LongestRisingSequenceFinder>();

            return services;
        }
    }

// Inside Unit test class we should be able to get the method data to check the test cases

public class UnitTests
        {
            [Theory]
            [InlineData(new [] {4,3,5,8,5,0,0,-3}, new [] {3,5,8})]
            public async Task CanFind(IEnumerable<int> data, IEnumerable<int> expected)
            {
                IEnumerable<int> actual = null;
    
                // TODO: create the finder instance and get the actual result
    
                actual.Should().Equal(expected);
            }
        }
question from:https://stackoverflow.com/questions/65884965/how-to-access-the-method-which-is-available-in-the-service-collection-to-perform

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

1 Reply

0 votes
by (71.8m points)

As the commenters have noted, you are testing the class LongestRisingSequenceFinder. Good unit tests dispense with other concerns, and test one thing. Instead, skip service resolution, which is a completely separate concern.

Your test should look like

[Theory]
[InlineData(new [] {4,3,5,8,5,0,0,-3}, new [] {3,5,8})]
public async Task CanFind(IEnumerable<int> data, IEnumerable<int> expected)
{
    var finder = new LongestRisingSequenceFinder();

    // a guess on usage...
    var actual = finder.MethodOfFinder(...);
    
    actual.Should().Equal(expected);
}

If you're truly wanting to test service resolution with a call to the method, this is an integration test. A test like that is going to require constructing a test server, doing all the dependency injection, etc. in the context of the server.

Simply creating an artificial container as your code shows and then calling the method adds no value to testing. Think about it this way; your code was creating a container with 1 entry for the sole purpose of getting an entry. That's a really complicated way to instead just do new in your test, so adds no value.


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

...