I have recently applied this regex pattern attribute to one of the properties in my class in order to evaluate valid url formats. The problem has now occurred that AutoFixture cannot create an instance of it displaying the error
"AutoFixture was unable to create an instance from
Ploeh.AutoFixture.Kernel.RegularExpressionRequest, most likely because
it has no public constructor, is an abstract or non-public type."
I have tried a few suggestions like
var contact = _fixture.Build<ContactEntity>()
.With(c=>c.Customer.Website,
new SpecimenContext(_fixture)
.Resolve(new RegularExpressionRequest(Constants.UrlRegex)))
.Create();
and
public class WebsiteSpecimenBuilder: ISpecimenBuilder
{
public object Create(object request,
ISpecimenContext context)
{
var pi = request as PropertyInfo;
if (pi!=null && pi.PropertyType == typeof(string)
&& (pi.Name.Equals("Email") || pi.Name.Equals("Website")))
{
//tried both of these options
return (new OmitSpecimen() || "http://www.website.com";
}
return new NoSpecimen(request);
}
}
But i still can't get autofixture to create the class. Am i missing something to get it to create or is this regex too complex for autofixture to handle?
I seem to have gotten a solution by using the customize method as such:
_fixture = new Fixture();
_fixture.Customize<CustomerEntity>(ce =>
ce.With(x => x.Website, "http://suchTest.verwow"));
This returns any instance where the customer is called to have this website (or other regex properties). I don't really know if something in autofixture takes precedence as to why this one has worked in setting the website while the others haven't. But it is a solution that allows my testing to work
You should check the regex which is passed to RegularExpressionRequest()
new RegularExpressionRequest(Constants.UrlRegex)
The regex should be of generation type and not validation. For example, it can be as follows
string TopicSuffixValidation = #"[a-zA-Z0-9]{1,5}/[a-zA-Z0-9]{1,5}"
I use AutoFixture(4.17.0) and it implicitly referenced Fare(2.2.1)
You can do that:
var entity = new Fixture().Build<Entity>()
.With(x => x.variable, new Xeger(RegexPattern).Generate)
.Create();
Related
I have the following line in my mapper:
I am trying to map from one model where I have a single property called Result to a model where I have a List of Results.
I have the following so far:
options.CreateMap<Contract.Dto.Result, List<Result>>(MemberList.Source).ConvertUsing<ResultConverter>();
internal class ResultConverter : ITypeConverter<Contract.Dto.Result, List<Result>>
{
public List<Result> Convert(Contract.Dto.Result source, List<Result> destination, ResolutionContext context)
{
destination.Add(context.Mapper.Map<Contract.Dto.Result, Result>(source));
return destination;
}
}
However, when debugging, the ResultConverter is never hit.
Does anyone have any solution as to how to map from single object to list of objects? There will only ever be one object in this list of objects but other constraints stop me from amending the models.
I have managed to get this working in a very small Class Library I created. Bits I noticed that would potentially break your code:
No mention anywhere that you are also mapping < Contract.Dto.Result, Result > - ensure you have added both these maps
var config = new MapperConfiguration(options =>
{
options.CreateMap<Contract.Dto.Result, List<Result>>(MemberList.Source).ConvertUsing<ResultConverter>();
options.CreateMap<Contract.Dto.Result, Result>(MemberList.Source);
});
In your converter, I changed this to use a new list of results rather than destination
public List<Result> Convert(Contract.Dto.Result source, List<Result> destination, ResolutionContext context)
{
var listOfResults = new List<Result>();
var result = context.Mapper.Map<Contract.Dto.Result, Result>(source);
listOfResults.Add(result);
return listOfResults;
}
When actually using the map, just ensure you have got the correct syntax
var result = new Contract.Dto.Result();
var expected = mapper.Map<List<Result>>(result);
Also, if using IOC, make sure you have registered the conveters. Autofac code example below
builder.RegisterType<ResultConverter>().AsSelf();
builder.Register(context => new MapperConfiguration(options=>
{
options.CreateMap<Contract.Dto.Result, List<Result>>(MemberList.Source).ConvertUsing<ResultConverter>();
options.CreateMap<Contract.Dto.Result, Result>(MemberList.Source);
})).AsSelf().SingleInstance();
builder.Register(c =>
{
//This resolves a new context that can be used later.
var context = c.Resolve<IComponentContext>();
var config = context.Resolve<MapperConfiguration>();
return config.CreateMapper(context.Resolve);
}).As<IMapper>().InstancePerLifetimeScope();
As OP mentioned in comment below, also ensure that the correct types are used, in this instance List<> vs IList<>
Give each of these a try on your project, hopefully that will solve your issues. If not let me know and I can take a further look.
I didn't use automapper ever. You can try this and please let me know if it works:
//Use this method.
public void Map(object PreEqual, string PreEqProperty, object PostEqual, string PostEqProperty)
{
PreEqual.GetType().GetProperty(PreEqProperty).SetValue(PreEqual, PostEqual.GetType().GetProperty(PostEqProperty).GetValue(PostEqual, null), null);
}
//Use Map method somewhere you want, like this:
//myRefObj is your source object and myRefProp is its property that you want to map to other objects.
foreach(SomeType item in CollectionOfSomeType)
{
Map(item, "myRefProp", myRefObj, "myRefProp");
}
I think it will work with primitive types. Can you try and let me know if it works?
I want to make a factory class to return DbContext object where table name will be passed as string. There are more than 100 tables in database, each having a different structure/schema.
The idea is to pass tableName as string in the method which will return object in EF and we can select/update these records. I found this code in some article but have some confusion how to use it:
public ObjectContext Context(EntityObject entity)
{
var relationshipManager = ((IEntityWithRelationships)entity).RelationshipManager;
var wrappedOwnerProperty = relationshipManager.GetType().GetProperty("WrappedOwner", BindingFlags.Instance | BindingFlags.NonPublic);
var wrappedOwner = wrappedOwnerProperty.GetValue(relationshipManager);
var contextProperty = wrappedOwner.GetType().GetProperty("Context");
return (ObjectContext)contextProperty.GetValue(wrappedOwner);
}
I am not sure if this is what I need. Also what should I pass in EntityObject entity and where I should pass the tableName?
Please let me know if there is any other way to achieve the same thing.
One simple way to do this is to use the DbContext.Set() method, and get the type based on the string.
using (var db = new MyDbContext)
{
string tableName = "ApplicationUser";
var type = Assembly.GetExecutingAssembly()
.GetTypes()
.FirstOrDefault(t => t.Name == tableName);
if(type != null)
DbSet catContext = context.Set(type);
}
However, this has one drawback and that's that this is a non-generic DbSet (ie it's a DbSet not a DbSet<T>).
A way to get the Generic DbSet (which allows linq functionality) would be to do something like this:
using (var db = new IdentityDbContext())
{
string tableName = "ApplicationUser";
var type = Assembly.GetExecutingAssembly()
.GetTypes().FirstOrDefault(t => t.Name == tableName);
var method = db.GetType().GetMethods()
.First(x => x.IsGenericMethod && x.Name == "Set");
MethodInfo generic = method.MakeGenericMethod(type);
var set = generic.Invoke(db, null);
}
Of course set will be an object here, and you'll have to cast it somehow, which is still part of the problem.
When it boils down to it, if you aren't going to work with statically compiled types, you're going to have to keep dealing with reflection, particularly when you have generic types to deal with (ie DbSet<T>, among others). You have to get them cast to a static type at some point to call the methods, or keep doing MethodInfo.Invoke's.
Another option is to use dynamic, but you can't use dynamics with c# extension methods (without casting to a concrete type) so you're back in the same boat of no Linq support.
Using Linq by reflection is a huge pain.
To be honest, If you have 100 classes, I'd just bite the bullet and write the hard coded types, or use a code generator to do it for you like CodeSmith.
I've written a piece of code that is responsible for creating an Issue.It uses a visitor pattern to set the Issue assignee.
Here's the code :
public Issue CreateIssue(IssueType type, string subject, string description, Priority priority, string ownerId)
{
var issue = new Issue
{
...
};
IssueManagerContext.Current.IssueAssignmentMethodResolver(type).Visit(issue);
...
return issue;
}
I would like to test the functionality of this code thus somehow I need to mock the behavior of a visitor. After studying different Mock libraries I decided to use Moq.
But I don't know how should I build a mock object that gets an argument from my code instead of hard coding it as it's shown in the quick start guide.
Here's what I have done so far :
var visitor = new Mock<IIssueVisitor>();
visitor.Setup(x => x.Visit(null));
You can only match a specific instance of an object if the test has the same reference as the SUT. The problem in your scenario is that your SUT creates the instance issue, and returns it at the end of the method. Your test cannot access it while the method is executing, which precludes your mock object from being able to match it.
You can configure your mock object to match any Issue instance with the following syntax:
visitor.Setup(x => x.Visit(It.IsAny<Issue>()));
You can also configure the mock to conditionally match an Issue instance:
// Matches any instance of Issue that has an ID of 42
visitor.Setup(x => x.Visit(It.Is<Issue>(theIssue => theIssue.ID == 42)));
If you want to match the reference of a specific instance of Issue, then you'll have to move the instantiation logic into some kind of abstraction (e.g., a factory) of which your test could provide a fake implementation. For example:
// In SUT
var issue = issueFactory.CreateIssue();
...
// In test
var stubIssue = new Issue{ ... };
var issueFactory = new Mock<IIssueFactory>();
var visitor = new Mock<IIssueVisitor>();
...
issueFactory.Setup(factory => factory.CreateIssue())
.Returns(stubIssue);
visitor.Setup(x => x.Visit(stubIssue));
Use the following syntax:
interface IFoo
{
int Bar(string baz);
}
var mock = new Mock<IFoo>();
mock.Setup(x => x.Bar(It.IsAny<string>()))
.Returns((string baz) => 42 /* Here baz contains the value your code provided */);
I am trying to create a proxy type using mixins. In the following example, TypePresenter implements ICustomTypeDescriptor. When I create an instance the "GetProperties" throws a NotImplementedException.
When I do the same thing with ProxyGenerator.CreateClassProxy, everything works fine! I want to get the type so that I can use it with my IoC.
var options = new ProxyGenerationOptions();
options.AddMixinInstance(new TypePresenter<SampleViewModel>());
var builder = new DefaultProxyBuilder();
var sampleType = builder.CreateClassProxyType(typeof(SampleViewModel), null, options);
var sample = Activator.CreateInstance(sampleType);
var typeDescriptor = (ICustomTypeDescriptor)sample;
// Error happens on this line.
var properties = typeDescriptor.GetProperties();
var property = properties["DoIt"];
Assert.IsNotNull(property);
Assert.IsTrue(property.PropertyType == typeof(ICommand));
Why does this not work?
You are creating your sample object from the Activator; since you are not using the Castle-DynamicProxy library to create the proxy the mixin properties cannot work since the wiring behind the mixin is done via an intereceptor.
You can simply create the sample first via the ProxyGenerator then cast it to ICustomTypeDescriptor, you don't really need its type:
var options = new ProxyGenerationOptions();
options.AddMixinInstance(new TypePresenter<SampleViewModel>());
var pg = new ProxyGenerator();
var sample = pg.CreateClassProxy<SampleViewModel>(options);
// regarding
//var sampleType = sample.GetType();
var typeDescriptor = (ICustomTypeDescriptor)sample;
// Error doesn't happen anymore on this line.
var properties = typeDescriptor.GetProperties();
Edit
Reagrding building a type without knowing the constructor in advance, one can use the CreateClassProxy overload that takes an object[] of constructor parameters as an argument;
Given and interface that lets us define the parameters we will need for a type:
public interface IGiveConstructorParametersFor<T> {
object[] Parameters {get;}
}
it is possible to register it against a concrete class (or even multiple concrete classes that would then be resolved depending on the scenario we are in). Then we can have the following method to build a type we don't know in advance with constructor parameters we don't know in advance:
public T Proxify<T>(IGiveConstructorParametersFor<T> constructorParametersForT) {
var options = new ProxyGenerationOptions();
options.AddMixinInstance(new TypePresenter<T>());
var pg = new ProxyGenerator();
var sample = pg.CreateClassProxy(typeof(T),
null,
options,
constructorParametersForT.Parameters);
var typeDescriptor = (ICustomTypeDescriptor)sample;
var properties = typeDescriptor.GetProperties();
}
As long as any type can be mapped to an implementation of the constructor parameters interface at runtime, it doesn't need to know it beforehand
I have an interface with a CopyFrom() method that copies all properties from another object. I have a test that performs several VerifyGet() calls to ensure that each property was retrieved from the passed object, e.g.:
Thing target = new Thing();
IThing source = new Mock<IThing>();
target.CopyFrom(source.Object);
source.VerifyGet(t => t.Foo);
source.VerifyGet(t => t.Bar);
I'd like a way to iterate over the properties of IThing though and verify that each was copied automatically so the test will fail if someone adds a property but forgets to copy it. Is there a way to do this via Moq? I tried;
foreach (var prop in typeof(IThing).GetProperties())
{
source.VerifyGet(t => prop.Invoke(t, null));
}
but it didn't work since the lambda did not represent a property accessor. I think there should be a way to create something via the Expression class, but I am not familiar enough with LINQ to figure out what should be in there.
I don't think such a thing is possible with Moq, but first of all you need to question whether your test is relevant. What do you really wish to test here?
Is it important that the CopyFrom method reads any properties? It could definitely read all the properties without writing to them to the new instance, so such an Interaction-based test doesn't really prove anything.
I'm guessing that what you would really like to test is that the properties of the target are equal to the properties of the source?
Assuming that the properties on IThing are writable, you could create a Stub with all the properties set using the SetupAllProperties method:
var sourceStub = new Mock<IThing>();
sourceStub.SetupAllProperties();
sourceStub.Object.Bar = "Bar";
sourceStub.Object.Foo = "Foo";
You would then need to compare the target to the source to see if all properties match. You could do that by implementing a Test-Specific Equals method in a class that wraps the real target.
If you think that is too much work, you may want to check out AutoFixture's Likeness class that gives you a general-purpose Test-Specific equality comparison. That would allow you to continue the test like this:
var expectedResult = new Likeness<IThing>(sourceStub.Object);
target.CopyFrom(sourceStub.Object);
Assert.AreEqual(expectedResult, target);
Likeness uses Reflection to simply loop over all the public properties in the wrapped object and see if the compared object has the same values for those properties.
/// <summary>
/// Verifies that a property was read on the mock
/// </summary>
public static void VerifyGet<T>(this Mock<T> mockedObject, string propertyName) where T : class
{
var property = typeof(T).GetProperty(propertyName);
if (property == null)
throw new ArgumentException(string.Format("No property by the name '{0}' was found on '{1}'.", propertyName, typeof(T).Name));
// getPropFuncExpression = obj => obj.propertyName;
var parameterExpression = Expression.Parameter(typeof(T), typeof(T).Name);
var propertyExpression = Expression.Property(parameterExpression, property);
var getPropFuncExpression = Expression.Lambda(propertyExpression, parameterExpression);
var verifyGet = mockedObject.GetType().GetMethods().Single(m => m.Name == "VerifyGet" && m.GetParameters().Length == 1);
verifyGet.MakeGenericMethod(property.PropertyType).Invoke(mockedObject, new object[] { getPropFuncExpression });
}
You can add the above extension method so you can just call:
foreach (var prop in typeof(IThing).GetProperties())
{
source.VerifyGet(prop.Name);
}