Why does adding a constructor fail this MSpec test with System.InvalidOperationException? - castle-windsor

I have this first version of a class
public class GenerateAuthorisationWorkflows : IGenerateAuthorisationWorkflows
{
public IList<Guid> FromDtaObjects(IList<DtaObject> dtaObjects, Employee requestingEmployee)
{
foreach (var dtaObject in dtaObjects) { }
return new List<Guid>();
}
public IList<Guid> FromDtaObjects()
{
return new List<Guid>();
}
}
And the MSpec tests for it
public abstract class specification_for_generate_workflows : Specification<GenerateAuthorisationWorkflows>
{
protected static IWorkflowService workflowService;
Establish context = () => { workflowService = DependencyOf<IWorkflowService>(); };
}
[Subject(typeof(GenerateAuthorisationWorkflows))]
public class when_generate_workflows_is_called_with_a_dta_object_list_and_an_employee : specification_for_generate_workflows
{
static IList<Guid> result;
static IList<DtaObject> dtaObjects;
static Employee requestingEmployee;
Establish context = () =>
{
var mocks = new MockRepository();
var stubDtaObject1 = mocks.Stub<DtaObject>();
var stubDtaObject2 = mocks.Stub<DtaObject>();
var dtaObjectEnum = new List<DtaObject>{stubDtaObject1,stubDtaObject2}.GetEnumerator();
dtaObjects = mocks.Stub<IList<DtaObject>>();
dtaObjects.Stub(x => x.GetEnumerator()).Return(dtaObjectEnum).WhenCalled(x => x.ReturnValue = dtaObjectEnum);
requestingEmployee = mocks.Stub<Employee>();
mocks.ReplayAll();
};
Because of = () => result = subject.FromDtaObjects(dtaObjects, requestingEmployee);
It should_enumerate_the_dta_objects = () => dtaObjects.received(x=> x.GetEnumerator());
It should_call_workflow_host_helper = () => workflowService.AssertWasCalled(x => x.StartWorkflow());
}
With this configuration, my first test passes and my second test fails, as expected. I added a constructor to the class to inject the IWorkflowService.
public class GenerateAuthorisationWorkflows : IGenerateAuthorisationWorkflows
{
IWorkflowService _workflowService;
GenerateAuthorisationWorkflows(IWorkflowService workflowService)
{
_workflowService = workflowService;
}
public IList<Guid> FromDtaObjects(IList<DtaObject> dtaObjects, Employee requestingEmployee)
{
foreach (var dtaObject in dtaObjects)
{
Guid workflowKey = _workflowService.StartWorkflow();
}
return new List<Guid>();
}
public IList<Guid> FromDtaObjects()
{
return new List<Guid>();
}
}
Now, when I run the tests, they fail at the Because:
System.InvalidOperationException: Sequence contains no elements
at System.Linq.Enumerable.First(IEnumerable`1 source)
at MSpecTests.EmployeeRequestSystem.Tasks.Workflows.when_generate_workflows_is_called_with_a_dta_object_list_and_an_employee.<.ctor>b__4() in GenerateAuthorisationWorkflowsSpecs.cs: line 76
For clarity, line 76 above is:
Because of = () => result = subject.FromDtaObjects(dtaObjects, requestingEmployee);
I've tried tracing the problem but am having no luck. I have tried setting up a constructor that takes no arguments but it raises the same error. I have similar classes with IoC dependencies that work fine using MSpec/Rhino Mocks, where am I going wrong?

Castle Windsor requires a public constructor to instantiate a class. Adding public to the constructor allows correct operation.
public class GenerateAuthorisationWorkflows : IGenerateAuthorisationWorkflows
{
IWorkflowService _workflowService;
public GenerateAuthorisationWorkflows(IWorkflowService workflowService)
{
_workflowService = workflowService;
}
public IList<Guid> FromDtaObjects(IList<DtaObject> dtaObjects, Employee requestingEmployee)
{
foreach (var dtaObject in dtaObjects)
{
Guid workflowKey = _workflowService.StartWorkflow();
}
return new List<Guid>();
}
public IList<Guid> FromDtaObjects()
{
return new List<Guid>();
}
}

Rowan, looks like you answered your own question. It's good practice to explicitly state the access modifiers! By default, C# chooses private. These kinds of errors are easy to miss!
I can also see that your Establish block is too complicated. You're testing the implementation details and not the behavior. For example, you are
stubbing the GetEnumerator call that's implicitly made inside the foreach loop.
asserting that the workflow service was called only once
mixing MSpec automocking and your own local mocks
You're not actually testing that you got a GUID for every object in the input list. If I were you, I'd test the behavior like this...
public class GenerateAuthorisationWorkflows : IGenerateAuthorisationWorkflows
{
private readonly IWorkflowService _service;
public GenerateAuthorisationWorkflows(IWorkflowService service)
{
_service = service;
}
public List<Guid> FromDtaObjects(List<DtaObject> input, Employee requestor)
{
// I assume that the workflow service generates a new key
// per input object. So, let's pretend the call looks like
// this. Also using some LINQ to avoid the foreach or
// building up a local list.
input.Select(x => _service.StartWorkflow(requestor, x)).ToList();
}
}
[Subject(typeof(GenerateAuthorisationWorkflows))]
public class When_generating_authorisation_keys_for_this_input
: Specification<GenerateAuthorisationWorkflows>
{
private static IWorkflowService _service;
private static Employee _requestor = new Employee();
private static List<DtaObject> _input = new List<DtaObject>()
{
new DtaObject(),
new DtaObject(),
};
private static List<Guid> _expected = new List<Guid>()
{
Guid.NewGuid(),
Guid.NewGuid(),
};
private static List<Guid> _actual = new List<Guid>();
Establish context = () =>
{
// LINQ that takes each item from each list in a pair. So
// the service is stubbed to return a specific GUID per
// input DtaObject.
_input.Zip(_expected, (input, output) =>
{
DependencyOf<IWorkflowService>().Stub(x => x.StartWorkflow(_requestor, input)).Return(output);
});
};
Because of = () => _actual = Subject.FromDtaObjects(_input, _requestor);
// This should be an MSpec collection assertion that
// ensures that the contents of the collections are
// equivalent
It should_get_a_unique_key_per_input = _actual.ShouldEqual(_expected);
}

Related

Unit test with Moq returns Object reference not set to an instance of an object. when calling method Base.GetAsync()

I am trying to do a unit test with Moq for this method:
public class XsService : EntityResourceService<XModel, string>, IXResourceService<XModel, string>
{
private readonly IXsEntityRepository<XModel, string> XEntityRepository;
Public XsService(
iCorrelationContextAccessor correlationContextAccessor,
IJsonApiContext jsonApiContext,
IXsEntityRepository<XModel, string> XEntityRepository) :
base(jsonApiContext, XEntityRepository)
{
this.XEntityRepository = XEntityRepository;
}
public async Task<IEnumerable<XModel>> GetXsAsync(UModel uModel)
{
await XEntityRepository.GetAllAsync(uModel.UserId);
return await base.GetAsync();
}
}
This is my unit test:
var uModels = new List<UModel>()
{
new UModel { Id = "12341", Name="group_name1" },
new UModel { Id = "12342", Name="group_name1" }
};
[Fact]
public async Task GetUAsync_Ok()
{
//Mocking base class
var baseClassMock = new Mock<XsService>(correlationContextAccessor,
JsonApiContextMock.Object, userGroupsEntityRepositoryMock.Object) { CallBase = true };
baseClassMock.Setup(x => x.GetAsync()).Returns(Task.FromResult(uModels));
// Act
var res = baseClassMock.Object.GetXsAsync(parameter);
// Assert
Assert.Equal("", "");
}
the Error is thrown when reaching the line:
return await base.GetAsync();
Error:
System.NullReferenceException HResult=0x80004003 Message=Object reference not set to an instance of an object. Source=JsonApiDotNetCore StackTrace: at JsonApiDotNetCore.Services.EntityResourceService`3.GetAsyncd__8.MoveNext() at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
This exception was originally thrown at this call stack:
JsonApiDotNetCore.Services.EntityResourceServiceTResource, TEntity,
TId.GetAsync()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
Maybe I need to moq EntityResourceService, like this:
var eRS = new Mock<EntityResourceService<UModel, string>>(jsonApiContextMock.Object,
userGroupsEntityRepositoryMock.Object, null);
eRS.Setup(x => x.GetAsync()).Returns(Task.FromResult(userGroupModels));
var x = eRS.Object.GetAsync();
But, how can I inject that into the moq when creating the class instance?
This is the GetAsync method code
// MyModelService.cs
public class MyModelService : IResourceService<MyModel>
{
private readonly IMyModelDao _dao;
public MyModelService(IMyModelDao dao)
{
_dao = dao;
}
public Task<IEnumerable<MyModel>> GetAsync()
{
return await _dao.GetModelAsync();
}
}

Json.net contractResolver is failling

I have implemented the custom contract resolver to remove the some properties from serialized Json. Most of the time below code works but occasionally this code fails. Sometime it loops through the list and skips item I want to exclude which causing to appear that properties which I wanted to exclude.
class TestClass
{
public static void Test()
{
var objectToSerialise = //Coming from some WebAPI calls
string[] stringToSkip = {"skip1", "skip2"};
var settings = new JsonSerializerSettings
{
ContractResolver = new MyContractResolver(stringToSkip)
};
var json = JsonConvert.SerializeObject(objectToSerialise, settings);
}
}
public class MyContractResolver : DefaultContractResolver {
private string[] _skipthis;
public MyContractResolver(string[] skipthis)
{
_skipthis = skipthis;
}
private JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization){
var property = base.CreateProperty(member, memberSerialization);
property.ShouldSerialize = (prop) =>{
return !(_skipthis.Where(n => property.PropertyName.Contains(n)).Any());
};
return property;
}
}
Can someone please suggest why this code is failing silently intermittently with out throwing any kind of exception?
Note that skipthis array is not modified outside this. I want to skip the property when property name exist or substring of propertyname exist in skipthis array.

Binding StringElement (MT.D) with MvvmCross

We are using some MT.D StringElements, and their Value Property is bound to properties in the ViewModel.
The initial value is correctly shown but when the ViewModel changes some values and triggers PropertyChanged then the StringElements contain the good value but the display is not refreshed.
If we scroll the Controller or touch the StringElement then it is refreshed: the correct value is displayed.
Do you have any idea?
This is our ViewController
public class ContactView : MvxDialogViewController
{
public override void ViewDidLoad()
{
base.ViewDidLoad();
var bindings = this.CreateInlineBindingTarget<ContactViewModel> ();
Root = new RootElement()
{
new Section()
{
new StringElement("Company Name").Bind(bindings, vm => vm.CompanyName)
}
}
}
}
This is our ViewModel (simplified)
public class ContactViewModel : MvxViewModel
{
private string companyName;
public string CompanyName{
get{return companyName;}
set{companyName = value; RaisePropertyChanged(() => CompanyName);}
}
public async Task Init(string id)
{
var contact = await someService.SomeMethodAsync();
CompanyName = contact.CompanyName;
}
}
I found two solutions to my problem:
If I use UIView.Transition to replace the content then, in the new View, nothing is refreshed when I change the ViewModel (unless I scroll or tap it) UNLESS if the ViewModel properties have some default value non null and non empty
If I don't transition but use another method like this one to replace the content:
Sample code
MasterNavigationController.PopToRootViewController(false);
MasterNavigationController.ViewControllers = new UIViewController[] { viewController };
In this case the content is replaced and the view is refreshed when a ViewModel property changes: everything works correctly in this case.
I tried a viewmodel like:
public class FirstViewModel
: MvxViewModel
{
private Timer _timer;
private int _count;
public FirstViewModel()
{
_timer = new Timer(DoThis, null, 1000, 1000);
}
private void DoThis(object state)
{
_count++;
TextProperty = _count.ToString();
}
private string _textProperty = "T";
public string TextProperty
{
get { return _textProperty; }
set { _textProperty = value; RaisePropertyChanged(() => TextProperty); }
}
}
with a dialog view defined like:
Root = new RootElement("Example Root")
{
new Section("Debut in:")
{
new EntryElement("Login", "Enter Login name").Bind(bindings, vm => vm.TextProperty)
},
new Section("Debug out:")
{
new StringElement("Value is:").Bind(bindings, vm => vm.TextProperty),
};
It worked fine - ticking up every second...

Populating IEnumerable<class> with JSON result

I previously had the following line of code from within my AdminController that was successfully returning a list of relevant subsections from within a course:
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult GetCourseSections(int courseID)
{
var Sections = dbcontext.CourseSection.Where(cs => cs.CourseID.Equals(courseID)).Select(x => new
{
sectionID = x.CourseSectionID,
sectionTitle = x.Title
);
return Json(Sections, JsonRequestBehavior.AllowGet);
}
I was informed to take this out of the controller as it was bad practice to call dbcontext and so i moved this to the AdminViewModel. Within my AdminViewModel I have a variable public List CourseSectionList { get; set; } and I am trying to populate this variable with the JSON request details. My code is as follows:
AdminViewModel
public void GetCourseSectionDetails(int courseID)
{
var Sections = dbcontext.CourseSection.Where(cs => cs.CourseID.Equals(courseID)).Select(x => new CourseSection
{
CourseSectionID = x.CourseSectionID,
Title = x.Title
});
this.CourseSectionList = Sections.ToList();
}
AdminController
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult GetCourseSections(int courseID)
{
avm.GetCourseSectionDetails(courseID);
var Sections = avm.CourseSectionList.Where(cs => cs.CourseID.Equals(courseID)).Select(x => new
{
sectionID = x.CourseSectionID,
sectionTitle = x.Title
});
System.Diagnostics.EventLog.WriteEntry("Application", "JSON=" + Sections.ToList(), System.Diagnostics.EventLogEntryType.Error);
return Json(Sections, JsonRequestBehavior.AllowGet);
}
I am getting the error The entity or complex type 'MetaLearning.Data.CourseSection' cannot be constructed in a LINQ to Entities query. How can I populate this.CourseSectionList variable using the Sections?
As pointed by your error message, you can't, in linq to entities, use a
.Select(m => new <Entity>{bla bla})
where <Entity>... is one of your model's entity.
So either you use a "non model" class (DTO), which has the properties you need, or you have to enumerate before selecting (because linq to objects has not that limitation)
.ToList()
.Select(m => new <Entity>{bla bla});
You can find some nice explanations of why it's not possible here
EDIT :
you may also do something like that, if you wanna retrive only some properties of your entity, and don't wanna use a DTO :
return ctx
.CourseSection
.Where(cs => cs.CourseID.Equals(courseID))
//use an anonymous object to retrieve only the wanted properties
.Select(x => new
{
c= x.CourseSectionID,
t= x.Title,
})
//enumerate, good bye linq2entities
.ToList()
//welcome to linq2objects
.Select(m => new CourseSection {
CourseSectionID = m.c,
Title = m.t,
})
.ToList();
You don't need to repeat the same code in the controller, but directly pass the list to the view.
This being said I am informing you that placing data access code in your view model is even worse practice than keeping it in the controller. I would recommend you having a specific DAL layer:
public interface IRepository
{
public IList<CourseSection> GetSections(int courseID);
}
which would be implemented:
public class RepositoryEF : IRepository
{
public IList<CourseSection> GetSections(int courseID)
{
using (ctx = new YourDbContextHere())
{
return ctx
.CourseSection
.Where(cs => cs.CourseID.Equals(courseID))
.Select(x => new CourseSection
{
CourseSectionID = x.CourseSectionID,
Title = x.Title,
})
.ToList();
}
}
}
and finally have your controller take the repository as dependency:
public class SomeController : Controller
{
private readonly IRepository repo;
public SomeController(IRepository repo)
{
this.repo = repo;
}
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult GetCourseSections(int courseID)
{
var sections = this.repo.GetSections(courseID);
return Json(sections, JsonRequestBehavior.AllowGet);
}
}
I did this as follows using Darin's answer as a guide:
ViewModel
public void GetCourseSectionDetails(int courseID)
{
this.CourseSectionList = dbcontext.CourseSection.AsEnumerable().Where(cs => cs.CourseID.Equals(courseID)).Select(x => new CourseSection
{
CourseSectionID = x.CourseSectionID,
Title = x.Title
}).ToList();
}
Controller
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult GetCourseSections(int courseID)
{
var sections = avm.CourseSectionList;
return Json(sections, JsonRequestBehavior.AllowGet);
}

StructureMap DBServiceRegistry and MVC-mini-profiler?

If I use this code in each Repository class then I get SQL profiling to work but I want to move that code from each class into the class where StructureMap handles the DB.
Example of a Repository class:
public DB CreateNewContext()
{
var sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ConnectionString);
var profiledConnection = ProfiledDbConnection.Get(sqlConnection);
return DataContextUtils.CreateDataContext<DB>(profiledConnection);
}
public SqlRecipeRepository(DB dataContext)
{
_db = CreateNewContext();
}
Now I want the dataContext variable to be the profiled version and so come from my DBServiceRegistry class.
Here is the DBServiceRegistry class:
public class DBServiceRegistry : Registry
{
public DBServiceRegistry()
{
var sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["GetMeCooking.Data.Properties.Settings.server"].ConnectionString);
var profiledConnection = ProfiledDbConnection.Get(sqlConnection);
For<DB>().HybridHttpOrThreadLocalScoped().Use(() => DataContextUtils.CreateDataContext<DB>(profiledConnection));
//Original method just had this:
//For<DB>().HybridHttpOrThreadLocalScoped().Use(() => new DB());
}
}
This code does not cause any errors but I don't get the SQL profiling, what am I doing wrong?
The comment is correct, by creating the sql connection outwith the For line, you are overriding the scope command.
Far better to encapsulate the whole lot into an anonymous delegate
using System.Configuration;
using System.Data.SqlClient;
using System.Threading.Tasks;
using StructureMap;
using StructureMap.Configuration.DSL;
using Xunit;
public class DBServiceRegistry : Registry
{
private string connString = ConfigurationManager.ConnectionStrings["GetMeCooking.Data.Properties.Settings.server"].ConnectionString;
public DBServiceRegistry()
{
For<DB>().HybridHttpOrThreadLocalScoped().Use(
() =>
{
var sqlConnection = new SqlConnection(connString);
var profiledConnection = new StackExchange.Profiling.Data.ProfiledDbConnection(sqlConnection, MiniProfiler.Current);
return DataContextUtils.CreateDataContext<DB>(profiledConnection);
});
}
}
You can use unit tests to verify that the scope is correct (test syntax is xunit.net)
public class DBRegistryTests : IDisposable
{
private Container container;
public DBRegistryTests()
{
// Arrange (or test setup)
container = new Container(new DBServiceRegistry());
}
[Fact]
public void ConnectionsAreSameInThread()
{
// Create two connections on same thread
var conn1 = container.GetInstance<DB>();
var conn2 = container.GetInstance<DB>();
// Assert should be equal because hybrid thread is scope
// and test executes on same thread
Assert.Equal(conn1, conn2);
// Other assertions that connection is profiled
}
[Fact]
public void ConnectionAreNotSameInDifferentThreads()
{
var conn1 = container.GetInstance<DB>();
// Request second connection from a different thread
// (for < c# 4.0 use Thread instead of task)
var conn2 = new Task<DB>(() => this.container.GetInstance<DB>());
conn2.Start();
conn2.Wait();
// Assert that request from two different threads
// are not the same
Assert.NotEqual(conn1, conn2.Result);
}
public void Dispose()
{
// Test teardown
container.Dispose();
}
}