简体   繁体   中英

Writing UnitTests for a Service Fabric Application Class

I am writing unit tests for a Service Fabric Application class. I am running into some errors which I don't understand how to fix. The class definition is of the sort:

namespace SearchService
{
    internal sealed class SearchServiceClass : StatelessService
    {
        //variables defined followed by constructor
        private string jsonStr;
        public SearchServiceClass(StatelessServiceContext context)
            : base(context)
        {
            //constructor stuff
        }
        
        public bool IsDataJsonLoaded
        {
            get
            {
                return !(jsonStr == null);
            }
        }
    }
}

The application has a test class defined as follows:

namespace SearchService.Tests
{
    //[TestClass]
    public class SearchServiceClassTest
    {
        [Fact]
        public void SearchServiceClassConstructor()
        {
           var searchServiceClass = new SearchServiceClass();
           Assert.True(searchServiceClass.IsDataJsonLoaded);
        }
    }
}

I get the following error:

There is no argument given that corresponds to the required formal parameter 'context' of 'SearchServiceClass.SearchServiceClass(StatelessServiceContext)'.

Could someone please tell me how to fix this?

Edit: I have been looking at ServiceFabric.Mocks. What I understand is that I need to use the MockStatelessServiceContextFactory.Default to create a mock context. How do I do this, is the following the right way?:

var searchServiceClass = new SearchServiceClass(MockStatelessServiceContextFactory.Default);

Yes, you can use the ServiceFabric.Mocks library, to create a test instance of your service by using the following code:

var serviceInstance = new SearchServiceClass(MockStatelessServiceContextFactory.Default);

As an alternative to the Default context, you can also build a customized instance:

var newUri = new Uri("fabric:/MockApp/OtherMockStatelessService");
var serviceTypeName = "OtherMockServiceType";
var partitionId = Guid.NewGuid();
var replicaId = long.MaxValue;
var context = new MockCodePackageActivationContext("fabric:/MyApp", "MyAppType", "Code", "Ver", "Context", "Log", "Temp", "Work", "Man", "ManVer");
var context = MockStatelessServiceContextFactory.Create(context, serviceTypeName, newUri, partitionId, replicaId);
var serviceInstance = new SearchServiceClass(context);

See this sample test and this one for more information.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM