We are busy developing a Composite Application Library (PRISM) applicationusing Visual Studio 2010, WPF and Silverlight 4.0. We have managed to get asnear as 100% code sharing between our WPF and Silverlight application becauseof the Telerik WPF/SL controls. Currently we are spending our time to write theUnit Tests for our Shell application and our common CAL modules before we startporting the existing application onto the new framework.
We have investigated standard Microsoft Visual Studio Unit Tests in additionto Rhino Mocks and Moq. We have had many troubles in getting both Rhino Mockand Moq to test our CAL application, specifically when it comes to testing theAsynchronous ICommand call-backs and the IEventAggregator subscriptions.
Yesterday we decided to investigate the Telerik JustMock mocking libraries,however we're still failing to completely test our CAL application.
Can you please provide us with a sample of testing an Asynchronous ICommandand a event publication and subscription using the IEventAggregator. I'm hopingthat JustMock is CAL friendly.
[TestMethod] |
[ExpectedException(typeof(ApplicationException))] |
public void Current_NotAvailable_ThrowsApplicationException() |
{ |
// Arrange |
Mock.Arrange(() => SPContext.Current).Throws(new ApplicationException("Not allowed to call SPContext.Current")); |
// Act |
SPContext currentContext = SPContext.Current; |
} |
[TestMethod] |
public void Current_CurrentContextIsFake_ReturnsFakeSPContext() |
{ |
// Arrange |
var fakeContext = Mock.Create<SPContext>(); |
Mock.Arrange(() => SPContext.Current).Returns(fakeContext); |
// Act |
SPContext currentContext = SPContext.Current; |
// Assert |
Assert.IsNotNull(currentContext, "The current SPContext should not be null"); |
} |
[TestMethod] |
public void ShouldAssertNestedPropertySetups() |
{ |
var foo = Mock.Create<IFoo>(); |
Mock.Arrange(() => foo.Bar.Value).Returns(10); |
Assert.Equal(10, foo.Bar.Value); |
} |
[TestMethod] |
public void SPWeb_AllowAnonymousAccess_ReturnsTrue() |
{ |
// Arrange |
var fakeContext = Mock.Create<SPContext>(); |
Mock.Arrange(() => fakeContext.Web.AllowAnonymousAccess).Returns(true); |
// Assert |
Assert.IsTrue(fakeContext.Web.AllowAnonymousAccess, "Our SPWeb should allow anonymous access"); |
} |
[TestMethod] |
public void CurrentWeb_AllowAnonymousAccess_ReturnsTrue() |
{ |
// Arrange |
var fakeContext = Mock.Create<SPContext>(); |
Mock.Arrange(() => SPContext.Current).Returns(fakeContext); |
var fakeWeb = Mock.Create<SPWeb>(); |
Mock.Arrange(() => fakeContext.Web).Returns(fakeWeb); |
Mock.Arrange(() => fakeWeb.AllowAnonymousAccess).Returns(true); |
// Assert |
Assert.IsTrue(SPContext.Current.Web.AllowAnonymousAccess, "Anonymous access should be allowed on our current SPWeb"); |
} |
[SetUp] |
public void SetUp() |
{ |
ServiceLocatorInitializer.Init(); |
_provider = new NHibernateMembershipProvider(CreateMockUserRepository()); |
var cs = ConfigurationManager.ConnectionStrings; |
var config = new NameValueCollection |
{ |
{"applicationName", "PerformanceTracker"}, |
{"name", "NHibernateMembershipProvider"}, |
{"requiresQuestionAndAnswer", "false"}, |
{"connectionStringName", "membershipProviderConnectionString"} |
}; |
_provider.Initialize(config["name"], config); |
} |
// Doesn't work |
[Test] |
public void CanGetUserByEmail() |
{ |
string email = "marykate2@gmail.com"; |
string username = _provider.GetUserNameByEmail(email); // always null so it always fails. Repo mocked below |
Assert.AreEqual("marykate2", username); |
} |
// Works fine |
[Test] |
public void CanGetUserByUserKey() |
{ |
string email = "marykate2@gmail.com"; |
MembershipUser usr = _provider.GetUser(Guid.Empty, false); |
Assert.AreEqual(usr.Email, email); |
} |
private IRepositoryWithTypedId<User, Guid> CreateMockUserRepository() |
{ |
var called = false; |
var mockedDbContext = Mock.Create<IDbContext>(); |
Mock.Arrange(() => mockedDbContext.BeginTransaction()).DoInstead(() => called = true); |
var mockedRepository = Mock.Create<IRepositoryWithTypedId<User, Guid>>(); |
Mock.Arrange( |
() => |
mockedRepository.Get(Arg.Any<Guid>())).Returns(CreateUser()); |
Mock.Arrange( |
() => |
mockedRepository.FindOne(Arg.Any<IDictionary<string, object>>())).Returns(CreateUser()); |
Mock.Arrange(() => mockedRepository.DbContext).Returns(mockedDbContext); |
return mockedRepository; |
} |
private User CreateUser() |
{ |
User user = CreateTransientUser(); |
EntityIdSetter.SetIdOf<Guid> (user, new Guid(0x9b84e442, 0x125c, 0x487b, 0x9f, 0x17, 0x18, 0x26, 0xd8, 0xe4, 0x40, 0x72)); |
return user; |
} |
/// <summary> |
/// Creates a valid, transient User; typical of something retrieved back from a form submission |
/// </summary> |
private User CreateTransientUser() |
{ |
User user = new User() |
{ |
UserName = "marykate2", |
FirstName = "Mary", |
LastName = "Kate", |
LastActivityDate = new DateTime(), |
Email = "marykate2@gmail.com" |
}; |
return user; |
} |
/// <summary> |
/// Gets the user name associated with the specified e-mail address. |
/// </summary> |
/// <returns> |
/// The user name associated with the specified e-mail address. If no match is found, return null. |
/// </returns> |
/// <param name="email">The e-mail address to search for. </param> |
public override string GetUserNameByEmail(string email) |
{ |
User user = null; |
_userRepository.DbContext.BeginTransaction(); |
try |
{ |
user = _userRepository.FindOne(new Dictionary<string, object> {{"Email", email}}); |
} |
catch (Exception e) |
{ |
throw new ProviderException(e.Message); |
} |
if (user == null) |
return String.Empty; |
return user.UserName; |
} |
using (OptimumWebRollEntities context = new OptimumWebRollEntities()) |
{ |
returnList = (from u in context.OptimumUser |
where u.IsOptimumStaff == false |
&& u.IsActive |
&& u.Region.RegionId == regionId |
orderby u.Surname, u.FirstName |
select new data.ReportingEntities.Candidate() |
{ |
OptimumUserId = u.OptimumUserId, |
FirstName = u.FirstName, |
Surname = u.Surname |
}).ToList(); |
} |
///
<summary>
///
///</summary>
[
TestMethod()]
[
ExpectedException(typeof(InvalidPluginExecutionException))]
public void ExecuteRequiredFieldTelerikTest()
{
ContactRequiredFieldsPlugin target = new ContactRequiredFieldsPlugin(string.Empty, string.Empty);
var context = TelerikMock.Mock.Create<IPluginExecutionContext>(); //!!!!!!!!! Fails here
var service = TelerikMock.Mock.Create<ICrmService>();
TelerikMock.Mock.Arrange(() => context.CreateCrmService(true)).Returns(service);
DynamicEntity
entity = new DynamicEntity(EntityName.contact.ToString());
entity.Properties.Add(
new StringProperty("telephone1", ""));
entity.Properties.Add(
new StringProperty("emailaddress1", ""));
context.InputParameters[
ParameterName.Target] = entity;
target.Execute(context);
}
SPSite site = SPContext.Current.Site; |
SPSecurity.RunWithElevatedPrivileges(delegate() { |
using (SPSite mysite = new SPSite(site.ID)) { |
using (SPWeb myweb = mysite.OpenWeb()) { |
SPList = myweb.Lists["List_Name"]; |
// do something else |
} |
} |
}); |