Writing a Unit Test to ensure dynamic proxy creation by testing for IEntityWithChangeTracker (EF4) - visual-studio-2010

I've been working through Julie Lerman's books on Entity Framework, and I've run into somewhat of a snag...
In "Programming Entity Framework DbContext" on page 66 Julie suggests writing a Unit Test to make sure that dynamic proxies are being created, since the requirements for getting Entity Framework to create change tracking proxies are fairly simple, but also very easy to miss.
With that being said, I followed the general structure of Julie's example to write the following test for my code:
[Test]
public void IsDynamicProxy()
{
using (var scienceFairToGoContext = new ScienceFairToGoContext())
{
var scienceFair = scienceFairToGoContext.ScienceFairs.Create();
Assert.IsTrue(scienceFair is IEntityWithChangeTracker);
}
}
When I hover over the scienceFair object its pretty obvious its a change tracking proxy
System.Data.Entity.DynamicProxies.ScienceFair_D3C57A2F699E75F716E63553D950EF7EC75F0C603F69093FCD78122CC0D6452C
...but whenever I run the unit test it always fails because "scienceFair is IEntityWithChangeTracker" always evaluates to false.
It appears as though someone else ran into this issue as well and posted it to the O'Reilly forums, but there doesn't seem to be a solution posted, nor do my Google searches return any type of answer.
I'm currently using Visual Studio 2010, EF4, NUnit, and running my tests through ReSharper. It's also worth mentioning that if run the code in a simple console application and debug it I get the same results.

Actually, it looks like I figured out the issue. While working through Julie's book, I thought it would be a good idea to have all of the entities inherit from a base class, ScienceFairToGoEntity.
It looks like I forgot to mark the 4 properties I had on the base class (InsertBy, InsertDate, UpdateBy, UpdateDate) as virtual, so the dynamic proxies were for Lazy Loading/ Relationship Fix-up and not for Change Tracking.

It's weird to find this non-working piece of code in such a good book. You can however execute you test by:
using (var scienceFairToGoContext = new ScienceFairToGoContext())
{
var scienceFair = scienceFairToGoContext.ScienceFairs.Create();
Assert.IsTrue(scienceFair.GetType().IsSubclassOf(typeof(ScienceFair)));
}
although it is less generally applicable when there are entities in inheritance hierarchies. With derived entities you'd have to use
scienceFairToGoContext.BaseEntities.Create<TDerivedEntity>()

Related

How to Inject Controller for MVC4/VS2012/Web API

I have read or tried to read far too many "how to"s on this and have gotten exactly nowhere. Unity? System.Web.Http.Dependencies? Ninject? StructureMap? Ugh. I just want something simple that works! I just can't figure out what the current state of this is. There are wildly different approaches and the examples appear to be incomplete. Heck the best lead had a sample project with it ... that I can't load in VS2010 or 2012. ARG! I waster 3/4 of the day on something that I feel should have been half an hour at most and move on! It's just plumbing!
I have a repository that's based on generics to process a number of data sets that all support the same operations.
IRepository
I want to control which repository each data set is bound to. This will allow me to bind everything to a test XML repository, transitioning them over to a SQL repository as the project advances.
I sure would appreciate some help getting this going! Thank you!
Sounds like you are at the state I was a couple of years ago.
Note, if you need any further help I cn send you some code. It's just hard to put all the code in here.
Ill try to explain the current architecture in the project I am working on. This post is a bit long winded but I am trying to give you a big picture of how using IOC can help you in many ways.
So I use Ninject. After trying to use Castle Windsor for a while I found Ninject easy to get up and running. Ninject has a cool website that will get you started.
First of all my project structure is as follows: (top down and it's MVC)
View - razor
ViewModel - I use 1 view model per view
ViewModelBuilder - Builds my view models for my views (used to abstract code away from my controller so my controller stays neat and tidy)
AutoMapper - to map domain entities to my view models
Controller - calls my service layer to get Domain Entities
Domain Entities - representations of my domain
ServiceLayer (business layer) - Calls my repository layer to get Domain entities or collections of these
AutoMapper again - to map custom types from my 3rd party vendors into my domain entities
RepositoryLayer - does CRUD operations to my data stores
This is a hierarchy but Domain entities kind of sit along side and are used in a few different layer.
Note: some extra tools mentioned in this post are:
AutoMapper - maps entities to other entities - eliminates the need to write loads of mapping code
Moq - Allows you to mock stuff for unit testing. This is mentioned later.
Now, regarding Ninject.
Each layer is marked with an interface. This must be done so Ninject can say to its self.
When I find IVehicleRepository inject it with a real VehicleRepository or even inject it with FakeVehicleRepository if I need a fake.
(this relates to your comment - "This will allow me to bind everything to a test XML repository")
Now every layer has a contstructor so that Ninject (or any other IOC container) can inject what it needs to:
public VehicleManager(IVehicleRepository vehicleRepository)
{
this._vehicleRepository = vehicleRepository;
}
VehicleManager is in my serviceLayer (not to be confused with anything to do with web services). The service layer is really what we would call the business layer. It seems that a lot of people are using the word service. (even though I think it is annoying as it makes me think about web services or WCF instead of just a business layer.... anyway...)
now without getting into the nitty gritty of Ninject setup the following line of code in my NinjectWebCommon.cs tells ninject what to do:
kernel.Bind<IVehicleRepository>().To<VehicleRepository>().InRequestScope();
This says:
Hey Ninject, when I ask for IVehicleRepository give my a concrete implementation of VehicleRepository.
As mentioned before I could replace VehicleRepository with FakeVehicleRepository so that I didnt have to read from a real database.
So, as you can now imagine, every layer is only dependent on interfaces.
I dont know how much unit testing you have done but you can also imagine that if you wanted to unit test your service layer and it had concrete references to your repository layer then you would not be able to unit test as you would be ACTUALLY hitting your repository and hence reading from a real database.
Remember unit testing is called unit testing because it tests ONE thing only. Hence the word UNIT. So because everything only knows about interfaces, it means that you can test a method on your service layer and mock the repository.
So if your service layer has a method like this:
public bool ThisIsACar(int id)
{
bool isCar = false;
var vehicle = vehicleRepository.GetVehicleById(id);
if(vehicle.Type == VehicleType.Car)
{
isCar = true;
}
else
{
isCar = false;
}
}
You would not want the vehicleRepository to be call so you could Moq what the VehicleRepository gives you back. You can mostly only Mock stuff if it implements an interface.
So your unit test would look like this (some pseudo code here):
[TestMethod]
public void ServiceMethodThisIsACar_Returns_True_When_VehicleIsACar()
{
// Arrange
_mockRepository.Setup(x => x.ThisIsACar(It.IsAny<int>)).returns(new Car with a type of VehicleType.Car)
// Act
var vehicleManager = new VehicleManager(_mockVehicleRepository.Object);
var vehicle = vehicleManager.ThisIsACar(3);
// Assert
Assert.IsTrue(vehicle.VehicleType == VehicleType.Car)
}
So as you can see, at this point and it is very simplified, you only want to test the IF statement in your service layer to make sure the outcome is correct.
You would test your repository in its own unit tests and possibly mock the entity frame work if you were using it.
So, overall, I would say, use what ever IOC container gets you up and running the fastest with the least amount of pain.
I would also say, try and unit test all that you can. This is great for a few different reasons. Obviously it tests the code you have written but it will also immediately show you if you have done some thing stupid like new-ing up a concrete repository. You will quickly see that you wont have an interface to mock in your unit tests and this will lead you to go back and refactor your code.
I found that with IOC, it takes a while to just get it. It confuses the crap out of you until one day it just clicks. After that it is so easy you wonder how you ever lived without it.
Here is a list of things I cant live without
Automapper
Moq
Fluent Validation
Resharper - some hate it, I love it, mostly for its unit testing UI.
Anyway, this is getting too long. Let me know what you think.
thanks
RuSs

BDD solution testing of different layers outside-in

Recently, I got started reading on BDD and TDD and I got hooked. I got lost with the amount of unorganized sources of information and different opinions of what's best and what not. At the end I settled on xBehave & xUnit. I like the fluent syntax and the ease of defining the behaviors with Fluent Assertions and Fluent Validation.
I'm also trying to implement the onion architecture with a test project I'm working on for learning. Here's my scenario: The project, to make it simple, is a product tracker. I can create products and track who owns it. I want to implement two specs:
when a new product is created without a name then an error should be displayed
when a new product is created without an owner assigned then an error should be displayed.
I created the spec which instantiated a new Product and a new ProductService which in turns creates the Product. The spec passes and the validation is occuring now the question is:
How do I test my ProductRepository class? Do I test it next or mock it and finish all specs first then come back and test repository classes?
Should I have mocked the ProductService class in the first spec?
Is that done at the unit test level? should i create a unit test class?
Wouldn't testing the repository make it an integration test?
so far, I don't have a UI and i'm writing my specs for the domain, service, and infrastructure layers.
do i need to use watin for my UI tests?
would switching to watin/specflow makes more sense and would save on efforts to have fully tested layers from top to bottom?
Here's one of the specs I worked on:
[Scenario]
public void creating_new_product_without_a_name_should_throw_error()
{
var productService = default(IProductService);
var action = default(Action);
_
.Given("a new product", () =>
productService = new ProductService() as IProductService)
.When("creating the new product without a name", () =>
action = () => productService.Create(new Product()))
.Then("it should should display an error", () =>
action.ShouldThrow<ValidationException("Name is required."));
}
Thank you for your reply in advance and, please, if you are answering this thread back up with some materials/articles/sample code on to why your suggestion would be better to follow.
It sounds like you are testing small parts and then plan to glue them together into something big. This is (IMO, againt) not TDD (and certainly not BDD): you are not letting the tests drive the design/architecture.
To start with, don't think that much about the design. Don't think onion architecture, don't think repositories, don't think services.
Start by writing a test that verifies the whole solution, from end to end. Make that test as small as possible. To start with, just verify that e.g. a label is displayed. Then write the smallest solution that you can think of to make the test pass. Then write another test and the solution for that.
After a while, have a look at the code (production, but also test) to find resposibilities. Is there an embryo of a service in there somewhere? Extract it! But don't do it prematurely. Let the code tell you what it wants to look like.
Start thinking about the domain (Product, Owner, etc) up front and include it early in your code. Wait a little longer with persistance (repositories), but not too long.
Keep testing at this level (end-to-end). Add micro tests when necessary. So my answer to the question "how do I test my ProductRepository/Service class" is a question to you: do you need to? Or is it sufficiently covered by the end-to-end tests? If not, why?

How do you unit test when you need to explore code?

In TDD how should you continue when you know what your final outcome should be, but not the processing steps you need to get there?
For example your class is being passed an object whose API is completely new to you, You know the class has the information you need but you don't know how to retrieve it yet: How would you go about testing this?
Do you just focus on the desired result ignoring the steps?
Edit 1
package com.wesley_acheson.codeReview.annotations;
import com.sun.mirror.apt.AnnotationProcessor;
import com.sun.mirror.apt.AnnotationProcessorEnvironment;
public class AnnotationPresenceWarner implements AnnotationProcessor {
private final AnnotationProcessorEnvironment environment;
public AnnotationPresenceWarner(AnnotationProcessorEnvironment env) {
environment = env;
}
public void process() {
//This is what I'm testing
}
}
I'm trying to test this incomplete class. I want to test I have the right interactions with AnnotationProcessorEnvironment within the process method. However I'm unsure from the API docs what the right interaction is.
This will produce a file that contains details on the occurrence of each annotation within a source tree.
The actual file writing will probably be delegated to another class however. So this class' responsiblity is to create a representation of the annotation occurrences and pass that to whatever classes need to move it.
In non TDD I'd probably invoke a few methods set a breakpoint and see what they return.
Anyway I'm not looking for a solution to this specific example more sometimes you don't know how to get from A to B and you'd like your code to be test driven.
I'm basing my answer on this video:
http://misko.hevery.com/2008/11/11/clean-code-talks-dependency-injection/
If you have a model/business logic class that's supposed to get some data from a service then I'd go about this way:
Have your model class take the data that it needs in the constructor, rather than the service itself. You could then mock the data and unit test your class.
Create a wrapper for the service, you can then unit test then wrapper.
Perform a fuller test where you actually pass the data from the wrapper to the model class.
General Answer
TDD can be used to solve a number of issues, the first and foremost is to ensure that code changes do not break existing code in regards to their expected behavior. Thus, if you've written a class with TDD, you write some code first, see that it fails, then write the behavior to make it green without causing other tests to become red.
The side-effect of writing the test cases is that now you have Documentation. This means that TDD actually provides answers to two distinct problems with code. When learning a new API, regardless of what it is, you can use TDD to explore it's behavior (granted, in some frameworks this can be very difficult). So, when you are exploring an API, it's ok to write some tests to provide documentation to it's use. You can consider this a prototyping step as well, just that prototyping assumes you throw it away when complete. With the TDD approach, you keep it, so you can always return back to it long after you've learned the API.
Specific Answer to the Example Given
There are a number of approaches which attempt to solve the problem with the AnnotationProcessor. There is an Assertion framework which addresses the issue by loading the java code during the test and asserting the line which the error/warning occurs. And here on Stack overflow
I would create a prototype without the testing to get knowledge of how the api is working. When I got that understanding, I would continue on the TDD cycle on my project
I agree with Bassetassen. First do a spike to understand what is this external API call does and what you need for your method. Once you are comfortable with the API you know how to proceed with TDD.
Never ever Unit Test against an unknown API. Follow the same principle is if you didn't own the code. Isolate all the code you are writing from the unknown or unowned.
Write your unit tests as if the environmental processor was going to be code that you were going to TDD later.
Now you can follow #Tom's advice, except drop step 1. Step 2's unit tests now are just a matter of mapping the outputs of the wrapper class to calls on the API of the unknown. Step two is more along the lines of an integration test.
I firmly believe changing your flow from TDD to Prototyping to TDD is a loss in velocity. Stay with the TDD until you are done, then prototype.

How to unit test the Ook Language Integration example?

I am writing a custom language colorizer as a Visual Studio extension using MEF. Most of my code comes from the Ook Language Integration sample that is available here. My colorizer is pretty much ready, but now I need to provide an appropriate unit test suite for my implementation.
Given the MEF nature of this stuff, I wonder which is the appropriate approach to unit testing. Should I just directly reference my Tagger from my unit test and test the GetTags method? Should I involve MEF in my unit tests? Are there any examples out there about testing MEF based colorizers and custom Intellisense implementations?
OK, so I think I got an approach to do this. Don't know if it is the ideal approach, but allows me to test my core logic. The credits go to the guys behind the HQL Language Service for Visual Studio who showed me how to create stubs for ITextSnapshots and to Noah Richards whose Spell Checker extension has as set of unit tests that set the scenario for my ones.
Here the code for my TestFixture:
[TestFixture]
public class TokenTaggerTests
{
[Test]
public void CanGetTagsForSimpleSelect()
{
TestQuery("SELECT * FROM Books", new List<string>() { "SELECT", "*", "FROM", "Books"});
}
private void TestQuery(string query, List<string> expected)
{
ITextSnapshot snapshot = SnapshotUtil.CreateSnapshot(query);
NormalizedSnapshotSpanCollection spans = new NormalizedSnapshotSpanCollection(snapshot.CreateSpanFromLineNumber(0));
MyTokenTagProvider provider = new MyTokenTagProvider();
ITagger<ITag> tagger = provider.CreateTagger<ITag>(new Mock<ITextBuffer>().Object);
List<string> words = tagger.GetTags(spans).Select(s => query.Substring(s.Span.Start, s.Span.Length)).ToList();
string errorMessage = string.Format("Got list: [{0}]. Expected: [{1}]", string.Join(", ", words), string.Join(", ", expected));
CollectionAssert.AreEqual(expected, words, errorMessage);
}
}
In the TestQuery method I start by calling CreateSnapshot on SnapshotUtil. That is a useful class, found in the HQL Language Service test project that would create ITextSnapshot objects based on some input text, which simulates what VS would provide to my extension. Then I go and use MyTokenTagProvider to create a tagger for me. Here I use this powerful thing called Moq to create a Mock of an ITextBuffer object, which is the expected input parameter for CreateTagger.
Now that we have a tagger, the rest is just playing around with it to check if it is doing the job. GetTags is the core method I want to test here, as it is the one that will take my input query and output the series of tags it was able to identify. To get the actual words, we examine each tag's span and use it to extract the word from the original query. The CollectionAssert method of NUnit will make sure the output list of words matches the expected list.
Hopefully this is useful for anybody else out there creating and testing VS editor extensions.

VS.Net Unit Testing -- possible to have project-scoped test setup?

Within a test file (MyTest.cs) it is possible to do setup and teardown at the class and the individual test level. Do similar hooks exist for the entire project? Entire solution?
No I don't believe that they do.
Typically when people ask this question it's because they have tests whoch are depending on something heavy, like a DB setup which needs to be reset for each test pass. Usually the right thing to do here is to mock/stub/fake the dependency out and remove the part that's causing the issue. Of course your reasons for this may be completely different.
Updated: So thinking about this some more I think you could do something with attributes and static types. You could add an assembly level attribute to each test assembly and pass it a static type.
[OnLoadAttribute(typeof(ProjectInitializer))]
When the assembly loads the type will get resolved and it's static constructor will be executed the first time it's resolved (when the assembly is loaded).
Doing something at a solution level is much harder because it depends how your unit test runner deals with tests and how it loads tests into AppDomains, per test, per test class or per test project. I suspect most runners create a new AppDomain per project.
I'm not exactly recommending this as I haven't tried it and there may be some repercussions. It's an idea you might want to try. Another option would be do derive all your tests from a common base class which has a constructor which resolves a singleton that in turn does your setup. This is less hacky but means having a common base class. You could also use an aspect oriented approach I suspect.
Hope this helps. These are just thoughts as to how you could do this.
Ade
We use the [AssemblyInitialize] / [AssemblyCleanup] attributes for project level test setup and cleanup code. We do this for two things:
creating a test database
creating configuration files in a temp directory
It works fine for us, although we have to be careful that each test leaves the database how it found it. Looks a little like this (simplified):
[AssemblyInitialize]
public static void AssemblyInit(TestContext context)
{
ConnectionString = DatabaseHelper.CreateDatabaseFornitTests();
}
[AssemblyCleanup]
public static void AssemblyCleanup()
{
DatabaseHelper.DeleteDatabase(ConnectionString);
}
I do not know of a way to do this 'solution' wide (I guess this really means for the test run - across potentially multiple projects)

Resources