Add coded control to UIMap (Coded UI Test) - unit-testing

I would like to add a handwritten coded control to my UIMap.cs (not UIMap.Designer.cs).
For example, when I record: writing in a texBox, I get the following code in UIMap.Designer.cs:
public class Recorded_Writing_In_forRecordParams
{
public string UIForRecordEditText = "forRecord";
}
public class UIMainWindowWindow : WpfWindow
{
public UIMainWindowWindow()
{
this.SearchProperties[WpfWindow.PropertyNames.Name] = "MainWindow";
this.SearchProperties.Add(new PropertyExpression(WpfWindow.PropertyNames.ClassName, "HwndWrapper", PropertyExpressionOperator.Contains));
this.WindowTitles.Add("MainWindow");
}
public WpfEdit UIForRecordEdit
{
get
{
if ((this.mUIForRecordEdit == null))
{
this.mUIForRecordEdit = new WpfEdit(this);
this.mUIForRecordEdit.SearchProperties[WpfEdit.PropertyNames.AutomationId] = "forRecord";
this.mUIForRecordEdit.WindowTitles.Add("MainWindow");
}
return this.mUIForRecordEdit;
}
}
private WpfEdit mUIForRecordEdit;
}
I want use this control in my CodedUITest. Is there a way to search the TextBox in the UIMap.cs by own coded or to search it in my TestMethod? Which is the best way?

Thanks for the answer, but I solved my problem on my own with the following way:
UIMap.cs
public partial class TestLittleAppUIMap
{
private MyWindow mMyWindow;
public MyWindow MMyWindow
{
get
{
if (this.mMyWindow == null)
{
this.mMyWindow = new MyWindow();
}
return this.mMyWindow;
}
}
}
public class MyWindow : WpfWindow
{
private WpfEdit mWpfEdit;
public MyWindow()
{
this.SearchProperties[WpfWindow.PropertyNames.Name] = "MainWindow";
this.SearchProperties.Add(new PropertyExpression(WpfWindow.PropertyNames.ClassName, "HwndWrapper", PropertyExpressionOperator.Contains));
this.WindowTitles.Add("MainWindow");
}
public WpfEdit MWpfEdit
{
get
{
if ((this.mWpfEdit == null))
{
this.mWpfEdit = new WpfEdit(this);
#region Search Criteria
this.mWpfEdit.SearchProperties[WpfEdit.PropertyNames.AutomationId] = "forOwn";
this.mWpfEdit.WindowTitles.Add("MainWindow");
#endregion
}
return this.mWpfEdit;
}
}
CodedUI Test
[TestMethod]
public void TestLittleAppOwnMap()
{
this.UIMap.MMyWindow.MWpfEdit.DrawHighlight();
Playback.Wait(2500);
}
It is almost a copy of the designer class.
For searching directly in the TestMethod you can go like this:
[TestMethod]
public void TestLittleAppOwn()
{
WpfWindow w = new WpfWindow();
w.SearchProperties[WpfWindow.PropertyNames.Name] = "MainWindow";
w.SearchProperties.Add(new PropertyExpression(WpfWindow.PropertyNames.ClassName, "HwndWrapper", PropertyExpressionOperator.Contains));
w.DrawHighlight();
WpfEdit e = new WpfEdit(w);
e.SearchProperties[WpfEdit.PropertyNames.AutomationId] = "forOwn";
e.SetProperty("Text","myText");
e.DrawHighlight();
Playback.Wait(2500);
}
Where Playback.Wait just wait a short time for showing the Highlight.

Related

Request.GetOwinContext().getManager<ApplicationUserManager> returns null when unit testing Account controller web api

I am trying to write some unit tests for my account controller web apis which make use of UserManager but I keep receiving null on the line in the title in the following section:
public ApplicationUserManager UserManager
{
get
{
return _userManager ?? Request.GetOwinContext().GetUserManager<ApplicationUserManager>();
}
private set
{
_userManager = value;
}
}
I have tried so many different ways to fix this as I have read that I need to Mock some of the parts of ApplicationUser but have not managed to get any of them to fix my problem. Below is some of the code I have implemented following a tutorial to unit test:
public interface IStoreAppContext : IDisposable
{
//IDbSet<User> Users { get; }
DbSet<User> u { get; }
DbSet<SportProgram> SportContext { get; set; }
int SaveChanges();
void MarkAsModified(User item);
}
}
The api I am trying to unit test in my account controller is:
(This line below "var user..." is where the problem starts. it calls the line in the title of this question)
[Route("userProfile/{username}")]
public IHttpActionResult getUserProfile(String username)
{
var user = UserManager.FindByName(username);
if (user != null)
{
db2.MarkAsModified(user);
return Ok(user);
}
else
{
return NotFound();
}
}
Then in my TestProject I have the following context class:
class TestStoreAppContext : IStoreAppContext
{
public TestStoreAppContext()
{
this.u = new TestProductDbSet();
}
public DbSet<User> u { get; set; }
public DbSet<SportProgram> SportContext { get; set; }
public int SaveChanges()
{
return 0;
}
public void MarkAsModified(User item) { }
public void Dispose() { }
}
}
Finally in my test controller where i test the api:
[TestMethod()]
public void getUserProfileTest()
{
var context = new TestStoreAppContext();
context.u.Add(GetDemoProduct());
var controller = new AccountController(context);
var result = controller.getUserProfile("john") as OkNegotiatedContentResult<User>;
Assert.AreEqual("john", result.Content.UserName);
}
The GetDemoProduct called above:
User GetDemoProduct()
{
return new User()
{
Id = "3",
UserName = "john",
Password = "Password-1",
};
}
Can anyone point me in the right direction please?

Entity Framework 5 + Ninject: AutoDetectChanges issue with foreign keys

I'm trying to use the Onion Pattern with Generic Repositories + Unit of work + Entity Framework 5 + Ninject with Asp.net MVC4 but I'm having a problem with EF "DetectChanges" feature and I don't understand why I need to set it to "false".
Could you please help me?
My solution is to add the following line to the constructor of FindingBugContext.cs file:
Configuration.AutoDetectChangesEnabled = false;
In the commented lines of the following code, I'll explain more clearly my isssue.
It's a very simple (and maybe stupid) code reproducing the issue I don't understand and I didn't include the code for all interfaces because I think it's pretty simple to figure it out.
This is my service class, "RobotService.cs":
public class RobotService : IRobotService
{
private readonly IRepository<Body> _repoBody;
private readonly IRepository<BodyPart> _repoBodyPart;
private readonly IRepository<Robot> _repoRobot;
private readonly IUnitOfWork _unitOfWork;
public RobotService(
IRepository<Body> repoBody,
IRepository<BodyPart> repoBodyPart,
IRepository<Robot> repoRobot,
IUnitOfWork unitOfWork)
{
_repoBody = repoBody;
_repoBodyPart = repoBodyPart;
_repoRobot = repoRobot;
_unitOfWork = unitOfWork;
}
public Robot Get(int id)
{
Robot robot = new Robot();
robot = _repoRobot.Get(id);
if (robot != null)
{
Body body = _repoBody.Get(robot.BodyId);
/* FROM NOW ON:
* robot.BodyId = 0 --> instead of 1: WHY???
* robot.Name = "Robby1"
*/
if (body != null)
{
BodyPart head = new BodyPart();
head = _repoBodyPart.Get(body.HeadId);
body.Head = head;
/* FROM NOW ON:
* body.BodyId = 0 --> instead of 1: WHY???
* body.HeadId = 0 --> instead of 1: WHY???
* body.LeftArmId = 0 --> instead of 2: WHY???
* body.RightArmId = 0 --> instead of 3: WHY???
* body.BodyName = "Body1" --> doesn't change
*/
BodyPart leftArm = new BodyPart();
leftArm = _repoBodyPart.Get(body.LeftArmId);
body.LeftArm = leftArm;
BodyPart rightArm = new BodyPart();
rightArm = _repoBodyPart.Get(body.RightArmId);
body.RightArm = rightArm;
robot.Body = body;
}
}
return robot;
}
This is my custom code inside NinjectWebCommon.cs file after installation through NuGet package "Ninject.MVC3":
private static void RegisterServices(IKernel kernel)
{
kernel.Bind(typeof(IRepository<>)).To(typeof(RepositoryBase<>)).InRequestScope();
kernel.Bind<IDbContextFactory>().To<DbContextFactory>().InRequestScope();
kernel.Bind<IUnitOfWork>().To<UnitOfWork>().InRequestScope();
kernel.Bind<IRobotService>().To<RobotService>();
}
This is my DbContext class "FindingBugContext.cs":
public class FindingBugContext : DbContext
{
public FindingBugContext()
: base("FindingBugContext")
{
//Configuration.AutoDetectChangesEnabled = false; //This is the solution
}
public virtual void Commit()
{
base.SaveChanges();
}
private IDbSet<Robot> _robots;
private IDbSet<Body> _bodies;
private IDbSet<BodyPart> _bodyParts;
public virtual IDbSet<T> DbSet<T>() where T : class
{
return Set<T>();
}
public IDbSet<Robot> Robots
{
get { return _robots ?? (_robots = DbSet<Robot>()); }
}
public IDbSet<Body> Bodies
{
get { return _bodies ?? (_bodies = DbSet<Body>()); }
}
public IDbSet<BodyPart> BodyParts
{
get { return _bodyParts ?? (_bodyParts = DbSet<BodyPart>()); }
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
Database.SetInitializer(new DropCreateFindingBugWithSeedData());
modelBuilder.Configurations.Add(new RobotConfiguration());
modelBuilder.Configurations.Add(new BodyConfiguration());
modelBuilder.Configurations.Add(new BodyPartConfiguration());
}
public class DropCreateFindingBugWithSeedData : DropCreateDatabaseAlways<FindingBugContext>
{
protected override void Seed(FindingBugContext context)
{
BodyPart head = new BodyPart() { Type = PartType.Head, PartName = "Head" };
BodyPart leftArm = new BodyPart() { Type = PartType.LeftArm, PartName = "LeftArm" };
BodyPart rightArm = new BodyPart() { Type = PartType.RightArm, PartName = "RightArm" };
Body body = new Body() { BodyName = "Body1", Head = head, HeadId = 1, LeftArm = leftArm, LeftArmId = 2, RightArm = rightArm, RightArmId = 3 };
Robot robot = new Robot() { Name = "Robby1", BodyId = 1, Body = body };
context.Robots.Add(robot);
}
}
public class RobotConfiguration : EntityTypeConfiguration<Robot>
{
public RobotConfiguration()
{
ToTable("Robots");
HasKey(r => r.RobotId)
.Property(r => r.RobotId)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
HasRequired(r => r.Body)
.WithMany()
.HasForeignKey(r => r.BodyId);
}
}
public class BodyConfiguration : EntityTypeConfiguration<Body>
{
public BodyConfiguration()
{
ToTable("Bodies");
HasKey(b => b.BodyId)
.Property(b => b.BodyId)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
HasRequired(b => b.Head)
.WithMany()
.HasForeignKey(b => b.HeadId)
.WillCascadeOnDelete(false);
HasRequired(b => b.LeftArm)
.WithMany()
.HasForeignKey(b => b.LeftArmId)
.WillCascadeOnDelete(false);
HasRequired(b => b.RightArm)
.WithMany()
.HasForeignKey(b => b.RightArmId)
.WillCascadeOnDelete(false);
}
}
public class BodyPartConfiguration : EntityTypeConfiguration<BodyPart>
{
public BodyPartConfiguration()
{
ToTable("BodyParts");
HasKey(b => b.BodyPartId)
.Property(b => b.BodyPartId)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
}
}
}
These are my Entities:
public class Robot
{
public Robot() { Body = new Body(); }
public int RobotId { get; set; }
public string Name { get; set; }
public int BodyId { get; set; }
public Body Body { get; set; }
}
public class Body
{
public Body()
{
Head = new BodyPart();
LeftArm = new BodyPart();
RightArm = new BodyPart();
}
public int BodyId { get; set; }
public string BodyName { get; set; }
public int HeadId { get; set; }
public BodyPart Head { get; set; }
public int LeftArmId { get; set; }
public BodyPart LeftArm { get; set; }
public int RightArmId { get; set; }
public BodyPart RightArm { get; set; }
}
public class BodyPart
{
public int BodyPartId { get; set; }
public PartType Type { get; set; }
public string PartName { get; set; }
}
public enum PartType
{
Head,
LeftArm,
RightArm
}
This is the Unit of Work code:
public class UnitOfWork : IUnitOfWork
{
private readonly IDbContextFactory _dbContextFactory;
private FindingBugContext _context;
public UnitOfWork(IDbContextFactory dbContextFactory)
{
_dbContextFactory = dbContextFactory;
}
protected FindingBugContext FindingBugContext
{
get { return _context ?? (_context = _dbContextFactory.Get()); }
}
public void Commit()
{
FindingBugContext.Commit();
}
}
This is the Generic Repository code:
public class RepositoryBase<T> : IRepository<T> where T : class
{
private FindingBugContext _context;
private readonly IDbSet<T> _dbSet;
public RepositoryBase(IDbContextFactory dbContextFactory)
{
DbContextFactory = dbContextFactory;
_dbSet = FindingBugContext.Set<T>();
}
public IDbContextFactory DbContextFactory
{
get;
private set;
}
public FindingBugContext FindingBugContext
{
get { return _context ?? (_context = DbContextFactory.Get()); }
}
//Read
public T Get(int id)
{
return _dbSet.Find(id);
}
}
This is my ContextFactory code:
public class DbContextFactory : Disposable, IDbContextFactory
{
private FindingBugContext _context;
public FindingBugContext Get()
{
if (_context == null)
{
_context = new FindingBugContext();
return _context;
}
else
{
return _context;
}
}
public void Dispose()
{
if (_context != null)
{
_context.Dispose();
}
}
}

Mock with Rhino mock -MVVM

I am using Rhino mock for mocking in my test methods. Could someone please see the TODO part in the test method and help me to mock it?
This is my service interface:
public interface ICustomersServiceAgent
{
void GetCustomers(EventHandler<GetCustomersCompletedEventArgs> callback);
void SaveCustomer(POC.Model.Customer cust, EventHandler<SaveCustomerCompletedEventArgs> callback);
}
This is my ViewModel
public class CustomerVM : ViewModelBase
{
private Model.Customer _curentCustomer;
private RelayCommand _saveCommand;
private ICustomersServiceAgent ServiceAgent { get; set; }
private bool isSaved;
private RelayCommand _calculateAgeCommand;
private Decimal age;
private DateTime dateOfBirth;
public CustomerVM(ICustomersServiceAgent serviceAgent)
{
if (serviceAgent == null)
{
ServiceAgent = ServiceManager.GetCustomerServiceManagement();
}
else
{
ServiceAgent =serviceAgent;
}
WireCommands();
}
// if curent object is null then it should be intialize
public Model.Customer CurentCustomer
{
get { return _curentCustomer ?? (_curentCustomer = new Model.Customer()); }
set
{
if (_curentCustomer != value)
{
_curentCustomer = value;
OnPropertyChanged("CurentCustomer");
}
}
}
public RelayCommand CalculateAgeCommand
{
get;
private set;
}
private void WireCommands()
{
SaveCustomerCommand = new RelayCommand(SaveCustomer);
SaveCustomerCommand.IsEnabled = true;
CalculateAgeCommand = new RelayCommand(CalculateAge);
}
private void SaveCustomer()
{
var cus = CurentCustomer;
ServiceAgent.SaveCustomer(cus, (s, e) =>
{
IsSaved = e.Result;
});
}
private void CalculateAge()
{
Age = DateTime.Now.Year - DateOfBirth.Year;
}
public RelayCommand SaveCustomerCommand
{
get;
private set;
}
public bool IsSaved
{
get { return isSaved; }
set
{
isSaved = value;
OnPropertyChanged("IsSaved");
}
}
public decimal Age
{
get { return age; }
set {
age = value;
OnPropertyChanged("Age");
}
}
public DateTime DateOfBirth
{
get { return dateOfBirth; }
set {
dateOfBirth = value;
OnPropertyChanged("DateOfBirth");
}
}
}
I want to test the SaveCustomerCommand in ViewModel above.
So In the my test method, I want to mock the void SaveCustomer(POC.Model.Customer cust, EventHandler<SaveCustomerCompletedEventArgs> callback) method in the ICustomersServiceAgent interface.
This is my test method, see the ToDo part
[TestMethod]
public void SaveCustomerCommandTest()
{
var customerServiceMock = MockRepository.GenerateMock<ICustomersServiceAgent>();
var customerVM = new POC.SilverlightClient.ViewModel.CustomerVM(customerServiceMock);
// TO do : Code to mock SaveCustomer method ///////////////////////////////////
var saveCustomerCommand = customerVM.SaveCustomerCommand;
saveCustomerCommand.Execute(null);
Assert.IsTrue(customerVM.IsSaved);
}
Could someone please explain how I can do this?
I don't see why you need to mock SaveCustomer. All the private SaveCustomer method does is invoke the ServiceAgent service which you already are mocking. I assume the RelayCommand class invokes the delegate you're sending in the constructor parameter which is the call to SaveCustomer. Have you tried running the unit test in your question as-is?
Try following:
customerServiceMock.Stub(sa => sa.SaveCustomer(Arg<POC.Model.Customer>.Is.Anything, Arg<EventHandler<SaveCustomerCompletedEventArgs>>.Is.Anything)).WhenCalled(invocation =>
{
((EventHandler<SaveCustomerCompletedEventArgs>)invocation.Arguments[1])(
customerServiceMock,
new SaveCustomerCompletedEventArgs { Result = true });
});

Difference between a Repository Implementation using ObjectContext vs DbContext on EF 4.1

What could be the better implementation for STE, I heard about that DbContext is the simplest way to implement a Repo with EF, personally I take advantage of the EntityState, but there is any member on ObjectContext that could deliver more functionallity for my CRUD operations using Repo? at today I'm using a GenericRepository like this one :
public class GenericRepository<TEntity> where TEntity : class
{
internal DbContext context;
internal DbSet<TEntity> dbSet;
public GenericRepository(DbContext context)
{
this.context = context;
this.dbSet = context.Set<TEntity>();
}
public virtual IEnumerable<TEntity> Get(
Expression<Func<TEntity, bool>> filter = null,
Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
string includeProperties = "")
{
IQueryable<TEntity> query = dbSet;
if (filter != null)
{
query = query.Where(filter);
}
foreach (var includeProperty in includeProperties.Split
(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
{
query = query.Include(includeProperty);
}
if (orderBy != null)
{
return orderBy(query).ToList();
}
else
{
return query.ToList();
}
}
public virtual TEntity GetByID(object id)
{
return dbSet.Find(id);
}
public virtual void Insert(TEntity entity)
{
dbSet.Add(entity);
}
public virtual void Delete(object id)
{
TEntity entityToDelete = dbSet.Find(id);
Delete(entityToDelete);
}
public virtual void Delete(TEntity entityToDelete)
{
if (context.Entry(entityToDelete).State == EntityState.Detached)
{
dbSet.Attach(entityToDelete);
}
dbSet.Remove(entityToDelete);
}
public virtual void Update(TEntity entityToUpdate)
{
dbSet.Attach(entityToUpdate);
context.Entry(entityToUpdate).State = EntityState.Modified;
}
public virtual IEnumerable<TEntity> GetWithRawSql(string query, params object[] parameters)
{
return dbSet.SqlQuery(query, parameters).ToList();
}
}
I forgot to mention that also I'm using Unity, so the calls to Repository are like this way :
[Dependency]
public IUnityContainer Container { get; set; }
public List<Case> GetAll()
{
using (var context = Container.Resolve<ClaimEntities>())
{
var qry = (from c in context.Cases
select c).ToList();
return qry;
}
}
Self tracking entities are feature of ObjectContext - they are not supported in DbContext. If you want STEs you need to swap to ObjectContext API and use STEs T4 template to generate entities instead of your current POCOs.

Unit Test a CSLA Asynchronous Validation Rule

I have a validation rule on a CSLA Business Base stereotyped class. I'm having trouble figuring out how to unit test the validation rule as it includes an asynchronous callback lambda expression. Here's some example code:
using System;
using System.Collections.Generic;
using Csla;
using Csla.Validation;
namespace UnitTestCSLAAsyncValidationRule
{
public class BusinessObject : BusinessBase<BusinessObject>
{
protected static PropertyInfo<string> CodeProperty = RegisterProperty<string>(p => p.Code);
public string Code
{
get { return GetProperty(CodeProperty); }
set { SetProperty(CodeProperty, value); }
}
protected override void AddBusinessRules()
{
ValidationRules.AddRule(CodeValidator, new AsyncRuleArgs(CodeProperty));
}
public static void CodeValidator(AsyncValidationRuleContext context)
{
var code = (string) context.PropertyValues["Code"];
CodeList codeList;
CodeList.GetCodeList((o, l) =>
{
codeList = l.Object;
if (codeList.Contains(code))
{
context.OutArgs.Result = false;
context.OutArgs.Description = "Code already in use.";
}
else
{
context.OutArgs.Result = true;
}
});
context.Complete();
}
}
public class CodeList : List<string>
{
public static void GetCodeList(EventHandler<DataPortalResult<CodeList>> handler)
{
DataPortal<CodeList> dp = new DataPortal<CodeList>();
dp.FetchCompleted += handler;
dp.BeginFetch();
}
private void DataPortal_Fetch()
{
// some existing codes..
Add("123");
Add("456");
}
}
}
I would like to test this with a test similar to the following:
using NUnit.Framework;
namespace UnitTestCSLAAsyncValidationRule.Test
{
[TestFixture]
public class BusinessObjectTest
{
[Test]
public void CodeValidationTest()
{
var bo = new BusinessObject();
bo.Code = "123";
Assert.IsNotEmpty(bo.BrokenRulesCollection);
}
}
}
However, the test Assert runs before the async callback. Is this something UnitDriven could help with? I've had a look at it but can't see how to use it in this scenario.
Thanks,
Tom
Answered by JonnyBee on http://forums.lhotka.net/forums/p/10023/47030.aspx#47030:
using NUnit.Framework;
using UnitDriven;
namespace UnitTestCSLAAsyncValidationRule.Test
{
[TestFixture]
public class BusinessObjectTest : TestBase
{
[Test]
public void CodeValidationTest()
{
UnitTestContext context = GetContext();
var bo = new BusinessObject();
bo.ValidationComplete += (o, e) =>
{
context.Assert.IsFalse(bo.IsValid);
context.Assert.Success();
//Assert.IsNotEmpty(bo.BrokenRulesCollection);
};
bo.Code = "123";
context.Complete();
}
}
}
Please not there was a small bug in my validation rule method - the call to AsyncValidationRuleContext.Complete() needs to be inside the lambda.
Thanks,
Tom