How I Test my API call Method .NET 6 Moq X-Unit - asp.net-web-api

I have this Method on my service layer, my project is builded on DDD Architecture i want to know how I Test my method that calls and api without call the original service returning a post
I Mocked the Interface of Service but when i debug, not enters into the Method on my Service layer, i want to enter into the service method without do this make a real world call to the service that the method consumes
Service Layer Class Service.cs
public string UpdateCancellation(UpdateCancellationDTO ucDTO)
{
var e1 = _configuration.GetSection("CancellationEndpoint").Value;
var response = _httpClient.PostAsJsonAsync
(e1 + "Update/", ucDTO).Result;
var value = response.Content.ReadAsStringAsync().Result;
return response.StatusCode.ToString();
}
Test Layer Class
private readonly Mock<ICancellationService> _service;
private readonly IConfiguration _configuration;
private readonly HttpClient _httpclient;
public TestController()
{
_service = new Mock<ICancellationService>();
}
[Fact]
public void UpdateCancellation()
{
UpdateCancellationDTO ucDTO = new UpdateCancellationDTO
{
RegistrationCode = 0,
ApplicationDate = new DateOnly
(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day),
ClientName = "Test",
ContactNumber = "00",
Document = "00",
DocumentType = "cc",
Email = "#",
GenesysNotification = "S",
ProductNumber = "0",
ProductType = "0",
SendMail = "S"
};
_service.Setup(x => x.UpdateCancellation(ucDTO));
var controller = new CancellationController(_service.Object);
var service = new CancellationService
(_httpclient, _configuration);
var result = controller.UpdateCancellation(ucDTO);
result = "registration_code: 1";
Assert.Same("registration_code: 1", result);
}
or what is the best way to test my method?
Post Data
For my personal the unit testing sucks
XUnit Test my HttpClient method
Learn how to do this weird invention of UnitSucksTesting

Related

Unit Test The instance of entity type cannot be tracked because another instance with the same key value for {'Id'} is already being tracked

I am writing a webAPI unittest that have several test call for each method in the class. I am using UseInMemoryDatabase to create a database and loading test data.
I was getting the following error between each test method
The instance of entity type 'AppSettings' cannot be tracked because another instance with the same key value for {'myId '} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached
I added context.Database.EnsureDeleted(); and that removed the error for the Get method but it was still throwing the error in the delete and update unit test.
I can't figure how to removed this error for delete and update when I run all the test methods at once.
Any help is appreciated.
private MyDBContext context;
[TestInitialize]
public void SetUp()
{
var options = new DbContextOptionsBuilder<MyDBContext>()
.UseInMemoryDatabase(databaseName: "MyDB")
.Options;
context = new CACIDBContext(options);
context.Database.EnsureDeleted(); // this removed the error between the several GET test methods. but not the delete,update
context.AppSettings.Add(new AppSettings { myId = 1, MyName = "test1", MyValue = "test1" });
context.AppSettings.Add(new AppSettings { myId = 2, MyName = "test2", MyValue = "test2" });
context.AppSettings.Add(new AppSettings { myId = 3, MyName = "test3", MyValue = "test3" });
context.SaveChanges();
}
[TestMethod]
public void GetSettings()
{
var logger = new Mock<ILogger<SettingsRepository>>();
var caciDbContent = new Mock<CACIDBContext>();
sRepository settingRepository = null;
settingRepository = new sRepository (context, logger.Object);
List<AppSettings> settings = settingRepository.GetSettings().ToList();
Assert.AreEqual(3, settings.Count);
}
[TestMethod]
public void RemoveSetting()
{
var logger = new Mock<ILogger<sRepository>>();
var caciDbContent = new Mock<CACIDBContext>();
sRepository sRepository = null;
sRepository = new sRepository (context, logger.Object);
// test Get By AppSettingName
bool result = sRepository.RemoveSetting(new AppSettings { myId = 3, MyName = "test3", MyValue = "test3");
Assert.AreEqual(true, result);
}
Here is my c# code
public bool RemoveSetting(AppSettings setting)
{
try
{
myDbContent.AppSettings.Remove(setting);
}
catch (Exception ex)
{
logger.LogError($"Failed to removfe an existing appsetting: {ex}");
throw ex;
}
return (myDbContent.SaveChanges() > 0 ? true : false);
}
Adding the following line helped in my case, which is similar to yours.
context.ChangeTracker.Clear()
It is only available for EF Core 5.0 though. Source: Microsoft Docs

Calling Dynamics Web API with Entity metadata early binding

I would like to consume my organizations dynamics oData endpoint but with early bound classes. However, there are a lot of early bound tools out there and I wanted to know which one provides the best developer experience/least resistance?
For example, there is this one:
https://github.com/daryllabar/DLaB.Xrm.XrmToolBoxTools
https://github.com/yagasoft/DynamicsCrm-CodeGenerator
and so on. Is there a developer preference/method out there?
Early bound classes are for use with the Organization Service which is a SOAP service. The normal way to generate those classes is using CrmSvcUtil.
OData can be used in Organization Data Service or Web API, but those don't have Early Bound classes.
Further reading: Introducing the Microsoft Dynamics 365 web services
It's not impossible to use with standard SOAP Early bound class. We just have to be creative. If we work just with basic attributes (fields, not relationships, ecc) it seems possible. For example. for create and update, OData will not accept the entire early bounded class, just pass the attibutes:
class Program
{
static void Main(string[] args)
{
string token = System.Threading.Tasks.Task.Run(() => GetToken()).Result;
CRMWebAPI dynamicsWebAPI = new CRMWebAPI("https:/ORG.api.crm4.dynamics.com/api/data/v9.1/",
token);
CRMGetListOptions listOptions = new CRMGetListOptions
{
Select = new string[] { "EntitySetName" },
Filter = "LogicalName eq 'contact'"
};
dynamic entityDefinitions = dynamicsWebAPI.GetList<ExpandoObject>("EntityDefinitions", listOptions).Result;
Contact contact = new Contact
{
FirstName = "Felipe",
LastName = "Test",
MobilePhone = "38421254"
};
dynamic ret = System.Threading.Tasks.Task.Run(async () => await dynamicsWebAPI.Create(entityDefinitions.List[0].EntitySetName, KeyPairValueToObject(contact.Attributes))).Result;
}
public static async Task<string> GetToken()
{
string api = "https://ORG.api.crm4.dynamics.com/";
ClientCredential credential = new ClientCredential("CLIENT_ID", "CLIENT_SECRET");
AuthenticationContext authenticationContext = new AuthenticationContext("https://login.microsoftonline.com/commom/oauth2/authorize");
return authenticationContext.AcquireTokenAsync(api, credential).Result.AccessToken;
}
public static object KeyPairValueToObject(AttributeCollection keyValuePairs)
{
dynamic expando = new ExpandoObject();
var obj = expando as IDictionary<string, object>;
foreach (var keyValuePair in keyValuePairs)
obj.Add(keyValuePair.Key, keyValuePair.Value);
return obj;
}
}
It's a simple approach and I didn't went further.
Maybe we have to serealize other objects as OptionSets, DateTime (pass just the string) and EntityReferences but this simple test worked fine to me. I'm using Xrm.Tools.WebAPI and Microsoft.IdentityModel.Clients.ActiveDirectory. Maybe it's a way.
[Edit]
And so I decided to go and created a not well tested method to cast the attributes. Problems: We have to follow OData statments to use the API. To update/create an entity reference we can use this to reference https://www.inogic.com/blog/2016/02/set-values-of-all-data-types-using-web-api-in-dynamics-crm/
So
//To EntityReference
entityToUpdateOrCreate["FIELD_SCHEMA_NAME#odata.bind"] = "/ENTITY_SET_NAME(GUID)";
So, it's the Schema name, not field name. If you use CamelCase when set you fields name you'll have a problem where. We can resolve that with a (to that cute) code
public static object EntityToObject<T>(T entity) where T : Entity
{
dynamic expando = new ExpandoObject();
var obj = expando as IDictionary<string, object>;
foreach (var keyValuePair in entity.Attributes)
{
obj.Add(GetFieldName(entity, keyValuePair), CastEntityAttibutesValueOnDynamicObject(keyValuePair.Value));
}
return obj;
}
public static object CastEntityAttibutesValueOnDynamicObject(object attributeValue)
{
if (attributeValue.GetType().Name == "EntityReference")
{
CRMGetListOptions listOptions = new CRMGetListOptions
{
Select = new string[] { "EntitySetName" },
Filter = $"LogicalName eq '{((EntityReference)attributeValue).LogicalName}'"
};
dynamic entitySetName = dynamicsWebAPI.GetList<ExpandoObject>("EntityDefinitions", listOptions).Result.List[0];
return $"/{entitySetName.EntitySetName}({((EntityReference)attributeValue).Id})";
}
else if (attributeValue.GetType().Name == "OptionSetValue")
{
return ((OptionSetValue)attributeValue).Value;
}
else if (attributeValue.GetType().Name == "DateTime")
{
return ((DateTime)attributeValue).ToString("yyyy-MM-dd");
}
else if (attributeValue.GetType().Name == "Money")
{
return ((Money)attributeValue).Value;
}
else if (attributeValue.GetType().Name == "AliasedValue")
{
return CastEntityAttibutesValueOnDynamicObject(((AliasedValue)attributeValue).Value);
}
else
{
return attributeValue;
}
}
public static string GetFieldName<T>(T entity, KeyValuePair<string, object> keyValuePair) where T : Entity
{
switch (keyValuePair.Value.GetType().Name)
{
case "EntityReference":
var entityNameList = System.Threading.Tasks.Task.Run(async () => await dynamicsWebAPI.GetEntityDisplayNameList()).Result;
var firstEntity = entityNameList.Where(x => x.LogicalName == entity.LogicalName).FirstOrDefault();
var attrNameList = System.Threading.Tasks.Task.Run(async () => await dynamicsWebAPI.GetAttributeDisplayNameList(firstEntity.MetadataId)).Result;
return attrNameList.Where(x => x.LogicalName == keyValuePair.Key).Single().SchemaName + "#odata.bind";
case "ActivityParty":
throw new NotImplementedException(); //TODO
default:
return keyValuePair.Key;
}
}
Please, note that this approach do not seems fast or good in anyway. It's better if you have all this values as static so we can save some fetches
[Edit 2]
I just found on XRMToolBox a plugin called "Early bound generator for Web API" and it seems to be the best option. Maybe you should give it a try if you're still curious about that. I guess its the best approach.
The final code is this:
static void Main(string[] args)
{
string token = Task.Run(() => GetToken()).Result;
dynamicsWebAPI = new CRMWebAPI("https://ORG.api.crm4.dynamics.com/api/data/v9.1/",
token);
Contact contact = new Contact
{
FirstName = "Felipe",
LastName = "Test",
MobilePhone = "38421254",
new_Salutation = new EntityReference(new_salutation.EntitySetName, new Guid("{BFA27540-7BB9-E611-80EE-FC15B4281C8C}")),
BirthDate = new DateTime(1993, 04, 14),
};
dynamic ret = Task.Run(async () => await dynamicsWebAPI.Create(Contact.EntitySetName, contact.ToExpandoObject())).Result;
Contact createdContact = dynamicsWebAPI.Get<Contact>(Contact.EntitySetName, ret, new CRMGetListOptions
{
Select = new string[] { "*" }
}).Result;
}
and you have to change the ToExpandoObject on Entity.cs class (generated by the plugin)
public ExpandoObject ToExpandoObject()
{
dynamic expando = new ExpandoObject();
var expandoObject = expando as IDictionary<string, object>;
foreach (var attributes in Attributes)
{
if (attributes.Key == GetIdAttribute())
{
continue;
}
var value = attributes.Value;
var key = attributes.Key;
if (value is EntityReference entityReference)
{
value = $"/{entityReference.EntitySetName}({entityReference.EntityId})";
}
else
{
key = key.ToLower();
if (value is DateTime dateTimeValue)
{
var propertyForAttribute = GetPublicInstanceProperties().FirstOrDefault(x =>
x.Name.Equals(key, StringComparison.InvariantCultureIgnoreCase));
if (propertyForAttribute != null)
{
var onlyDateAttr = propertyForAttribute.GetCustomAttribute<OnlyDateAttribute>();
if (onlyDateAttr != null)
{
value = dateTimeValue.ToString(OnlyDateAttribute.Format);
}
}
}
}
expandoObject.Add(key, value);
}
return (ExpandoObject)expandoObject;
}
Links:
https://github.com/davidyack/Xrm.Tools.CRMWebAPI
https://www.xrmtoolbox.com/plugins/crm.webApi.earlyBoundGenerator/
We currently use XrmToolkit which has it's own version of early binding called ProxyClasses but will allow you to generate early binding using the CRM Service Utility (CrmSvcUtil). It does a lot more than just early binding which is why we use it on all of our projects but the early binding features alone would have me sold on it. in order to regenerate an entity definition all you do is right click the cs file in visual studio and select regenerate and it is done in a few seconds.
For my first 3 years of CRM development I used the XrmToolbox "Early Bound Generator" plugin which is really helpful as well.

Unit test WebApi2 passing header values

I am working on a project using WebApi2. With my test project I am using Moq and XUnit.
So far testing an api has been pretty straight forward to do a GET like
[Fact()]
public void GetCustomer()
{
var id = 2;
_customerMock.Setup(c => c.FindSingle(id))
.Returns(FakeCustomers()
.Single(cust => cust.Id == id));
var result = new CustomersController(_customerMock.Object).Get(id);
var negotiatedResult = result as OkContentActionResult<Customer>;
Assert.NotNull(negotiatedResult);
Assert.IsType<OkNegotiatedContentResult<Customer>>(negotiatedResult);
Assert.Equal(negotiatedResult.Content.Id,id);
}
Now I am moving onto something a little complicated where I need to access value from the request header.
I have created my own Ok() result by extending the IHttpActionResult
public OkContentActionResult(T content,HttpRequestMessage request)
{
_request = request;
_content = content;
}
This allows me to have a small helper that reads the header value from the request.
public virtual IHttpActionResult Post(Customer customer)
{
var header = RequestHeader.GetHeaderValue("customerId", this.Request);
if (header != "1234")
How am I meant to setup Moq with a dummy Request?
I have spent the last hour or so hunting for an example that allows me to do this with webapi however I cant seem to find anything.
So far.....and I am pretty sure its wrong for the api but I have
// arrange
var context = new Mock<HttpContextBase>();
var request = new Mock<HttpRequestBase>();
var headers = new NameValueCollection
{
{ "customerId", "111111" }
};
request.Setup(x => x.Headers).Returns(headers);
request.Setup(x => x.HttpMethod).Returns("GET");
request.Setup(x => x.Url).Returns(new Uri("http://foo.com"));
request.Setup(x => x.RawUrl).Returns("/foo");
context.Setup(x => x.Request).Returns(request.Object);
var controller = new Mock<ControllerBase>();
_customerController = new CustomerController()
{
// Request = request,
};
I am not really sure what next I need to do as I havent needed to setup a mock HttpRequestBase in the past.
Can anyone suggest a good article or point me in the right direction?
Thank you!!!
I believe that you should avoid reading the headers in your controller for better separation of concerns (you don't need to read the Customer from request body in the controller right?) and testability.
How I will do it is create a CustomerId class (this is optional. see note below) and CustomerIdParameterBinding
public class CustomerId
{
public string Value { get; set; }
}
public class CustomerIdParameterBinding : HttpParameterBinding
{
public CustomerIdParameterBinding(HttpParameterDescriptor parameter)
: base(parameter)
{
}
public override Task ExecuteBindingAsync(ModelMetadataProvider metadataProvider, HttpActionContext actionContext, CancellationToken cancellationToken)
{
actionContext.ActionArguments[Descriptor.ParameterName] = new CustomerId { Value = GetIdOrNull(actionContext) };
return Task.FromResult(0);
}
private string GetIdOrNull(HttpActionContext actionContext)
{
IEnumerable<string> idValues;
if(actionContext.Request.Headers.TryGetValues("customerId", out idValues))
{
return idValues.First();
}
return null;
}
}
Writing up the CustomerIdParameterBinding
config.ParameterBindingRules.Add(p =>
{
return p.ParameterType == typeof(CustomerId) ? new CustomerIdParameterBinding(p) : null;
});
Then in my controller
public void Post(CustomerId id, Customer customer)
Testing the Parameter Binding
public void TestMethod()
{
var parameterName = "TestParam";
var expectedCustomerIdValue = "Yehey!";
//Arrange
var requestMessage = new HttpRequestMessage(HttpMethod.Post, "http://localhost/someUri");
requestMessage.Headers.Add("customerId", expectedCustomerIdValue );
var httpActionContext = new HttpActionContext
{
ControllerContext = new HttpControllerContext
{
Request = requestMessage
}
};
var stubParameterDescriptor = new Mock<HttpParameterDescriptor>();
stubParameterDescriptor.SetupGet(i => i.ParameterName).Returns(parameterName);
//Act
var customerIdParameterBinding = new CustomerIdParameterBinding(stubParameterDescriptor.Object);
customerIdParameterBinding.ExecuteBindingAsync(null, httpActionContext, (new CancellationTokenSource()).Token).Wait();
//Assert here
//httpActionContext.ActionArguments[parameterName] contains the CustomerId
}
Note: If you don't want to create a CustomerId class, you can annotate your parameter with a custom ParameterBindingAttribute. Like so
public void Post([CustomerId] string customerId, Customer customer)
See here on how to create a ParameterBindingAttribute

Need Help Writing Unit Test that on Method that requires HttpContext.Current.User

I am trying to write some unit tests for my MVC3 project (the first tests for this project) and I am getting stumped. Basically, I have a MemberQueries class that is used by my MemberController to handle all the logic.
I want to start writing tests on this class and want to start with a simple example. I have a method in this class called IsEditModeAvailable which determines if the user is a member of the "Site Administrator" role or that the user is able to edit their own data, but no one elses. I determine the last requirement by comparing the passed in Id value to the HttpContext User property.
The problem that I'm running into is I don't know how to mock or inject the proper parameters into my unit tests when creating the MemberQueries object. I am using, NUnit, Moq and Ninject, but I'm just not sure how to write the code. If I'm just not structuring this properly, please let me know as I'm a complete noob to unit testing.
Here's a sample of the code from my MemberQueries class:
public class MemberQueries : IMemberQueries
{
private readonly IRepository<Member> _memberRepository;
private readonly IMemberServices _memberServices;
private readonly IPrincipal _currentUser;
public MemberQueries(IUnitOfWork unitOfWork, IMemberServices memberServices, IPrincipal currentUser)
{
_memberRepository = unitOfWork.RepositoryFor<Member>();
_memberServices = memberServices;
_currentUser = currentUser;
}
public bool IsEditModeAvailable(int memberIdToEdit)
{
if (_currentUser.IsInRole("Site Administrator")) return true;
if (MemberIsLoggedInUser(memberIdToEdit)) return true;
return false;
}
public bool MemberIsLoggedInUser(int memberIdToEdit)
{
var loggedInUser = _memberServices.FindByEmail(_currentUser.Identity.Name);
if (loggedInUser != null && loggedInUser.Id == memberIdToEdit) return true;
return false;
}
}
Here's a sample from my MemberServices class (which is in my domain project, referenced by MemberQueries):
public class MemberServices : IMemberServices
{
private readonly IRepository<Member> _memberRepository;
public MemberServices(IUnitOfWork unitOfWork)
{
_memberRepository = unitOfWork.RepositoryFor<Member>();
}
public Member Find(int id)
{
return _memberRepository.FindById(id);
}
public Member FindByEmail(string email)
{
return _memberRepository.Find(m => m.Email == email).SingleOrDefault();
}
}
Finally, here's the stub of the unit test I am trying to write:
[Test]
public void LoggedInUserCanEditTheirOwnInformation()
{
var unitOfWork = new UnitOfWork();
var currentUser = new Mock<IPrincipal>();
// I need to somehow tell Moq that the logged in user has a HttpContext.User.Name of "jdoe#acme.com"
var memberServices = new Mock<MemberServices>();
// I then need to tell Moq that it's FindByEmail("jdoe#acme.com") method should return a member with a UserId of 1
var memberQueries = new MemberQueries(unitOfWork, memberServices.Object, currentUser.Object);
// If the logged in user is "jdoe#acme.com" who has an Id of 1, then IsEditModeAvailable(1) should return true
Assert.IsTrue(memberQueries.IsEditModeAvailable(1));
}
It looks like you are trying to test the MemberQueries.IsEditModeAvailable method. You have 2 cases to cover here. The Site Administrators case and the case where there's a currently logged user whose id matches the one passed as argument. And since the MemberQueries class relies purely on interfaces you could mock everything:
[TestMethod]
public void EditMode_Must_Be_Available_For_Site_Administrators()
{
// arrange
var unitOfWork = new Mock<IUnitOfWork>();
var currentUser = new Mock<IPrincipal>();
currentUser.Setup(x => x.IsInRole("Site Administrator")).Returns(true);
var memberServices = new Mock<IMemberServices>();
var memberQueries = new MemberQueries(unitOfWork.Object, memberServices.Object, currentUser.Object);
// act
var actual = memberQueries.IsEditModeAvailable(1);
// assert
Assert.IsTrue(actual);
}
[TestMethod]
public void EditMode_Must_Be_Available_For_Logged_In_Users_If_His_Id_Matches()
{
// arrange
var unitOfWork = new Mock<IUnitOfWork>();
var currentUser = new Mock<IPrincipal>();
var identity = new Mock<IIdentity>();
identity.Setup(x => x.Name).Returns("john.doe#gmail.com");
currentUser.Setup(x => x.Identity).Returns(identity.Object);
currentUser.Setup(x => x.IsInRole("Site Administrator")).Returns(false);
var memberServices = new Mock<IMemberServices>();
var member = new Member
{
Id = 1
};
memberServices.Setup(x => x.FindByEmail("john.doe#gmail.com")).Returns(member);
var memberQueries = new MemberQueries(unitOfWork.Object, memberServices.Object, currentUser.Object);
// act
var actual = memberQueries.IsEditModeAvailable(1);
// assert
Assert.IsTrue(actual);
}
Actually there's a third case you need to cover: you have a currently logged in user, who is not a Site Administrator and whose id doesn't match the one passed as argument:
[TestMethod]
public void EditMode_Should_Not_Be_Available_For_Logged_In_Users_If_His_Id_Doesnt_Match()
{
// arrange
var unitOfWork = new Mock<IUnitOfWork>();
var currentUser = new Mock<IPrincipal>();
var identity = new Mock<IIdentity>();
identity.Setup(x => x.Name).Returns("john.doe#gmail.com");
currentUser.Setup(x => x.Identity).Returns(identity.Object);
currentUser.Setup(x => x.IsInRole("Site Administrator")).Returns(false);
var memberServices = new Mock<IMemberServices>();
var member = new Member
{
Id = 2
};
memberServices.Setup(x => x.FindByEmail("john.doe#gmail.com")).Returns(member);
var memberQueries = new MemberQueries(unitOfWork.Object, memberServices.Object, currentUser.Object);
// act
var actual = memberQueries.IsEditModeAvailable(1);
// assert
Assert.IsFalse(actual);
}
The good news is that you are passing the user as an IPrincipal into the code that needs it rather than referring to HttpContext.Current.User. All you should need to do is setup the mock IPrincipal so that it returns the vales you need for that test.
var mockIdentity = new Mock<IIdentity>();
mockIdentity.Setup(x => x.Name).Returns("joe#acme.com");
var mockPrincipal = new Mock<IPrincipal>();
mockPrincipal.Setup(x => x.Identity).Returns(mockIdentity.Object);

Unit test with Moq

I am using Moq for unit testing, and I am trying to write my first unit test. My layers are "Controller=>Service=>Repository".
(I am using unity and repository pattern.)
Whenever I run my unit test, the actual value is always 0 like _service.GetEquipStates().Count() = 0. I do not know where I am doing wrong. Please suggest.
My unit test code is the following one:
private ITestService _service;
private Mock<ITestRepository> RepositoryMoc;
[TestInitialize]
public void Initialize() {
RepositoryMoc= new Mock<ITestRepository>();
_service = new TestService(RepositoryMoc.Object)
}
[TestMethod]
public void GetEquipmentState() {
var stateList = new[] { new State { ID = 1, Desc= "test" } };
RepositoryMoc.Setup(es => es.GetStates(true)).Returns(stateList );
Assert.AreEqual(1, _service.GetStates().Count());
}
Your setup is done for the methode GetState with prameter true.
RepositoryMoc.Setup(es => es.GetStates(true)).Returns(stateList);
But your call in the Assert-Statement is for a method GetState without a parameter. Is the method GetState declared with a default parameter or do you have to functions (one with a bool parameter and one without)?
Just make your call in the assert-statement like this and it should work.
Assert.AreEqual(1, _service.GetStates(true).Count());
I have replicated your code in one of my solutions, and the test passes fine.
private Mock<IAccessor> RepositoryMoc;
private Controller _service;
[TestMethod]
public void TestMethod()
{
// Arrange
_service = new Controller();
RepositoryMoc = new Mock<IAccessor>();
_service.Accessor = RepositoryMoc.Object;
var stateList = new[] { new State { ID = 1, Desc = "test" } };
RepositoryMoc.Setup(es => es.GetStates(true)).Returns(stateList);
// Act & Assert
Assert.AreEqual(1, _service.GetStates().Count());
}
Is the code exactly as is in your solution ?

Resources