Sorting some result list by the ids of another list

by Oliver 24. June 2011 21:47

Imagine we have the following list of ids of some kind of objects and a mapping of some of the ids to some values (also int’s here): 1: var ids = new List<int> { 6, 2, 5, 3, 7 }; 2: var valueMap = new List<int[]> { new[] { 5, 15 }, new[] { 2, 12 }, new[] { 3, 13 } }; Now, if we want to return the results a.k.a. the valueMap in the same order we have the ids, we can use the LINQ extension method .Join()like this: 1: var joined = ids.Join(valueMap, id => id, arr => arr[0], (id, arr) => string.Format("id: {0} - value: {1}", id, arr[1])); Really convenient! Let’s look at the output: 1: Console.WriteLine(string.Join("\r\n", joined)); 2:  3: // Prints: 4: // id: 2 - value: 12 5: // id: 5 - value: 15 6: // id: 3 - value: 13 By the way, I use FastSharp to write and test this kind of small code snippets Happy Coding, Oliver

Mocking revisited – mocking a method and passing a parameter using FakeItEasy and Moq

by Oliver 21. June 2011 23:35

Finally, I’ve started mocking things in our kind of legacy project while building new functionality. Now, I wanted to replace some DAL service with a mock that would would just serve me some results instead of ramping up NHibernate, going to the DB and assembling all the entities for this test. At first I tried to use FakeItEasy as I liked the syntax more than that of Moq: 1: var _geoObjectServiceMock = A.Fake<IGeoObjectService>(); 2: var results = new List<int>{ 1, 2, 3, ... }; 3: A.CallTo(() => _geoObjectServiceMock.GetSearchResultIds(A<GeoObjectSearchDesc>.Ignored)) 4: .Returns(results); This was easy. Just fix up the result you want the method to return and set it up. Well – I needed more. I needed to return my results list dependent on the GeoObjectSearchDesc parameter passed to the method. In short: I did not find a way to do this. I searched Google and Stackoverflow but to no avail. What I did find was an example using Moq showing exactly what I wanted to do. From Moq’s QuickStart wiki page: 1: // access invocation arguments when returning a value 2: mock.Setup(x => x.DoSomething(It.IsAny<string>())) 3: .Returns((string s) => s.ToLower()); 4: // Multiple parameters overloads available So I quickly installed Moq using NuGet, e.g. from the Package Manager Console: 1: Install-Package Moq -project Tests Now I have something like this which is exactly what I was looking to do: 1: var _geoObjectServiceMock = new Mock<IGeoObjectService>(); 2: var results = new List<int>{ 1, 2, 3, ... }; 3: _geoObjectServiceMock.Setup(svc => svc.GetSearchResultIds(It.IsAny<GeoObjectSearchDesc>())) 4: .Returns<GeoObjectSearchDesc>(gosd => results.Take(gosd.PageSize).ToList()); That’s what I expected – to get control over the method parameter(s) inside the mock. Great! Thank you Moq. Happy Coding, Oliver

Mocking for the first time – a short overview of a few .NET mocking frameworks

by Oliver 25. March 2011 15:50

In my recent post Testing: trying to get it right I mentioned that a lot of our tests are of the dirty hybrid kind, somewhere between real Unit tests and real Integration tests. Focusing on the Unit test part, we’re looking into using a mocking framework right now to change the way we write tests – most of all to decouple the different components that we use in the application under test. Wanting to use the fresh and hype NuGet package manager to install the mocking frameworks, I chose among the ones that were both available there and also looked promising: RhinoMocks: the sample found in the introduction did not look at all inviting to me so I dropped this one Telerik JustMock (Free Edition) Moq FakeItEasy Really, it could not have been easier to get all these libraries into the project than using NuGet! Sample code So I went ahead and wrote a short and simple test just to get a feel of the syntax they offer. At first I wanted to mock a simple Repository using its interface. Here is what I ended up with: Telerik JustMock: using syntax from their quick start manual 1: public void MockRepositoryInterfaceTest() 2: { 3: // Arrange 4: var repo = Mock.Create<ITodoRepository>(); 5: Mock.Arrange(() => repo.Todos) 6: .Returns(new List<Todo> {new Todo {Description = "my todo"}}.AsQueryable); 7: 8: // Act + Assert 9: repo.Todos.ToList().Count.Should().Be.EqualTo(1); 10: } Moq: just visit the project homepage 1: public void MockRepositoryInterfaceTest() 2: { 3: // Arrange 4: var repo = new Mock<ITodoRepository>(); 5: repo.SetupGet(rep => rep.Todos) 6: .Returns(() => new List<Todo> {new Todo {Description = "my todo"}}.AsQueryable()); 7: 8: // Act + Assert 9: repo.Object.Todos.ToList().Count.Should().Be.EqualTo(1); 10: } FakeItEasy: just visit the project homepage 1: public void MockRepositoryInterfaceTest() 2: { 3: // Arrange 4: var repo = A.Fake<ITodoRepository>(); 5: A.CallTo(() => repo.Todos) 6: .Returns(new List<Todo> {new Todo {Description = "my todo"}}.AsQueryable()); 7: 8: // Act + Assert 9: repo.Todos.ToList().Count.Should().Be.EqualTo(1); 10: } In the first test-ride FakeItEasy and JustMock look pretty much identical, whereas the syntax Moq offers is a bit awkward with the SetupGet() method name and the need to call repo.Object to get the instance. I hope to examinate further differences in use as the project moves on. Mocking concrete classes Since we’re working with a large application that still has a lot of services and classes not implementing any interface I also wanted to make sure we’ll be able to mock concrete types. Well, this didn’t go so well: JustMock and FakeItEasy simply returned an instance of the concrete class I gave them, Moq complains that it can’t override the Todos member. So I added the virtual modifier to it and the test is now green. Still, I got the impression that I was trying to do something that I shouldn’t. The following blog post motivates further not to mock concrete classes: Test Smell: Mocking concrete classes. So I guess introducing interfaces as a kind of contract between classes is the way to go, but in the meantime and where we can’t avoid mocking concrete types we’ll be left using Moq. That’s it for now, happy coding! Oliver

C# access modifiers: protected internal vs. protected vs. internal

by Oliver 27. January 2011 22:50

As I just read here on msdn, the modifiers protected and internal are orthogonal as in that they can be specified in all combinations and are combined with a logical OR. This means: protected members are accessible from inheriting classes internal members are accessible from classes within the same assembly protected internal classes are accessible from inheriting classes and all classes from the same assembly The last option is maybe the most unclear – but just imagine a subclass defined in a different assembly and you’ll see what this might be good for :-) Happy Coding, Oliver

About Oliver

shades-of-orange.com code blog logo I build web applications using ASP.NET and have a passion for javascript. Enjoy MVC 4 and Orchard CMS, and I do TDD whenever I can. I like clean code. Love to spend time with my wife and our children. My profile on Stack Exchange, a network of free, community-driven Q&A sites

About Anton

shades-of-orange.com code blog logo I'm a software developer at teamaton. I code in C# and work with MVC, Orchard, SpecFlow, Coypu and NHibernate. I enjoy beach volleyball, board games and Coke.