问题
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);
回答1:
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.
来源:https://stackoverflow.com/questions/65321526/writing-unittests-for-a-service-fabric-application-class