I use Xamarin and ReactiveUI to do mobile apps.
I'd like to test my ViewModel and its ReactiveCommand.
I register an asynchronous operation which return an IObservable inside the ReactiveCommand.
In ViewModel constructor :
Login = new ReactiveCommand();
var loginResult = Login.RegisterAsync(_ => Client.Login(Username, Password));
loginResult.ObserveOn(RxApp.MainThreadScheduler).BindTo(this, self => self.ConnectedUser);
Login
.Where(_ => ConnectedUser != null)
.Subscribe(_ => {
ConnectedUser.Disconnect();
ConnectedUser = null;
});
What's in Client.Login :
return Observable.Start(async () => {
// Do an HTTP POST to login the user, with await stuff in
// Return the User on success or throw an exception on error
}, RxApp.TaskpoolScheduler)
.Select(task => task.Result);
How to test the ViewModel login success ? Here is my approach which doesn't work :
[Test]
public void TestLoginSuccess()
{
ViewModel viewModel = new ViewModel();
viewModel.Username = "toto";
viewModel.Password = "****";
viewModel.Login.Execute(null);
Assert.That(viewModel.ConnectedUser, Is.Not.Null); // always null so fail :(
}
The test fails because the assertion is made before the command has finished executing.
Resolution
I was subscribing to the Login command and assumed that my "disconnection block" would be called before the RegisterAsync's one. Inverted the two would resolve the issue or simply put the "disconnection" logic inside RegisterAsync like this :
var loginResult = Login.RegisterAsync(_ => {
if (ConnectedUser != null)
{
ConnectedUser.Disconnect();
ConnectedUser = null;
}
Client.Login(Username, Password);
});
Paul Betts ' solution was also necessary.
TaskPoolScheduler is not set to Scheduler.Immediate, so it really is running in the background. Try this:
Scheduler.CurrentThread.With(sched => {
// TODO: Write your code here, now both schedulers are
// rigged to CurrentThread.
});
Related
I'm running into this problem, let me describe it with my code: https://github.com/UnoSD/Moq.Dapper/issues/20
I'm trying to mock a QueryAsync call using Moq.Dapper library and hitting the error:
Multi-map error: splitOn column 'Id' was not found
Here is the multi mapping query and code that works perfect:
var query = $#" SELECT * FROM [{nameof(Dashboard)}] dashboard
left join [{nameof(DashboardUser)}] dusers on dashboard.DashboardId = dusers.DashboardId
left join [Users] users on dusers.UserId = users.Id
WHERE dashboard.{nameof(accountId)} = #{nameof(accountId)} AND dashboard.{nameof(dashboardId)} = #{nameof(dashboardId)}";
Dashboard? dashboardEntity = null;
using (var connection = _context.CreateConnection())
{
var result = await connection.QueryAsync<Dashboard, DashboardUser, User, Dashboard?>(query,
(dashboard, dashboardUser, user) =>
{
if (dashboard == null) return null;
if (dashboardEntity == null)
{
dashboardEntity = dashboard;
dashboardEntity.Users = new List<DashboardUser>();
}
if (dashboardUser != null)
{
dashboardEntity.Users.Add(dashboardUser);
if (user != null) dashboardUser.User = user;
}
return dashboardEntity;
}, splitOn: $#"{nameof(Dashboard.DashboardId)},{nameof(Dashboard.DashboardId)},Id", param: new { accountId, dashboardId });
}
When Mocking the QueryAsync call I'm hitting the same problem as everyone else in the GitHub thread:
Func<Dashboard, DashboardUser, User, Dashboard?> funMap = (Dashboard, DashboardUser, User) => Mock.Of<Dashboard>();
public async Task Should_Get_Dashboard()
{
// Arrange
var connection = new Mock<DbConnection>();
IEnumerable<Dashboard> expected = GenFu.ListOf<Dashboard>(1);
connection.SetupDapperAsync(c => c.QueryAsync(It.IsAny<string>(), funMap, It.IsAny<object>(), It.IsAny<IDbTransaction>(),It.IsAny<bool>(),
"DashboardId,DashboardId,Id", // <-- SplitOn defined but error is *Multi-map error: splitOn column 'Id' was not found*
It.IsAny<int?>(), It.IsAny<CommandType?>()))
.ReturnsAsync(expected);
_context.Setup(x => x.CreateConnection()).Returns(connection.Object);
var dashboardRepository = new DashboardRepository(_context.Object, null, null);
CommonResult<Dashboard?> actual = new();
// Act
actual = await dashboardRepository.GetDashboard(3, 1);
}
Does anyone have a solution for this? It's the final thing for my Unit Test code coverage.
UPDATE:
I don't need to specify the mapping. See how the code TFirst, TSecond, TThird, TResult is faint/dimmed and I get the same problem even with it explicitly mapped:
I did try this method:
connection.SetupDapperAsync(c => c.QueryAsync<Dashboard>(It.IsAny<string>(), It.IsAny<Type[]>(), GetFunc, It.IsAny<object>(), It.IsAny<IDbTransaction>(), It.IsAny<bool>(), $#"{nameof(Dashboard.DashboardId)},{nameof(Dashboard.DashboardId)},Id", It.IsAny<int?>(), It.IsAny<CommandType?>()))
.ReturnsAsync(expected);
and got the error:
System.ArgumentException : When using the multi-mapping APIs ensure you set the splitOn param if you have keys other than Id (Parameter 'splitOn')
I checked the Dapper code and tried * for the SplitOn and that made no difference.
UPDATE 2:
The problem is the MultiMapAsync method and I can't mock it because its scope is private:
UPDATE 3:
I changed the Dapper method to Public to see if I could Mock it:
Func<Dashboard, DashboardUser, User, Dashboard?> funMap = (Dashboard, DashboardUser, User) => Mock.Of<Dashboard>();
private class DontMap { /* hiding constructor */ }
public async Task Should_Get_Dashboard()
{
// Arrange
var connection = new Mock<DbConnection>();
IEnumerable<Dashboard> expected = GenFu.ListOf<Dashboard>(1);
connection.SetupDapperAsync(c => c.MultiMapAsync<Dashboard, DashboardUser, User, DontMap, DontMap, DontMap, DontMap, Dashboard?>(new CommandDefinition(It.IsAny<string>(), It.IsAny<object>(), It.IsAny<IDbTransaction>(), It.IsAny<int>(),It.IsAny<CommandType>(), CommandFlags.None, default), funMap, $#"{nameof(Dashboard.DashboardId)},{nameof(Dashboard.DashboardId)},Id")).ReturnsAsync(expected);
I get the error:
Specified method is not supported
Mocking Dapper extension methods provides no value. You end up just testing your own test code. I would do either an integration test, where you test the whole method on a small database, or pull the testable logic out of the Dapper call like this:
using (var connection = _context.CreateConnection())
{
var result = await connection.QueryAsync<Dashboard, DashboardUser, User, Dashboard?>(query,
(dashboard, dashboardUser, user) => CreateDashboardEntity(dashboardEntity, dashboard, dashboardUser, user),
splitOn: $#"{nameof(Dashboard.DashboardId)},{nameof(Dashboard.DashboardId)},Id", param: new { accountId, dashboardId });
}
public Dashboard? CreateDashboardEntity(Dashboard? dashboardEntity, Dashboard dashboard, DashboardUser dashboardUser, User user)
{
if (dashboard == null) return null;
if (dashboardEntity == null)
{
dashboardEntity = dashboard;
dashboardEntity.Users = new List<DashboardUser>();
}
if (dashboardUser != null)
{
dashboardEntity.Users.Add(dashboardUser);
if (user != null) dashboardUser.User = user;
}
return dashboardEntity;
}
Now you can unit-test CreateDashBoardEntity as much as you like, and there is no logic left in QueryAsync that haven't already been tested by the good Dapper developers.
I'm trying to understand why the following unit test does not execute the callback. If I modify the code so that the UpdateWorklowInstanceState method only contains 2 parameters (Guid and IList), it works. However, something about having 3 parameters interferes.
What I mean by interferes is that the Callback doesn't appear to get executed. There's no error message. I expect to see the "Error Occurred" message but instead receive an "Element Updated" message which means the Callback did not populate the resultMessages with the NotificationMessage.
public void BusinessObjectReturnsErrorNotification_ReturnErrorMessage()
{
var workflowInstanceGuid = Guid.NewGuid();
var workflowElementModel = new WorkflowElementModel
{
ElementName = "ValidName",
WorkflowInstanceId = workflowInstanceGuid.ToString()
};
var workflowElementInstance = new WorkflowElementInstance
{
ElementName = workflowElementModel.ElementName,
FullDescription = "Full Description",
SummaryDescription = "Summary Description",
RefTime = DateTime.Now,
ElementType = "ElementType"
};
var mockWebApiBusinessObject = new Mock<IWebApiBusinessObject>();
mockWebApiBusinessObject.Setup(m => m.UpdateWorkflowInstanceState(workflowInstanceGuid, workflowElementInstance, It.IsAny<List<NotificationMessage>>()))
.Callback<Guid, WorkflowElementInstance, IList<NotificationMessage>>(
(workflowInstanceId, elementDetails, resultMessages) =>
{
resultMessages.Add(new NotificationMessage("An Error Occured!", MessageSeverity.Error));
});
var controller = new WorkflowElementController(mockWebApiBusinessObject.Object);
var result = controller.UpdateWorkflowElement(workflowElementModel);
Assert.AreEqual("An Error Occured!", result.Content.ReadAsStringAsync().Result);
}
Method under test:
[HttpPost]
[ActionName("UpdateWorkflowElement")]
public HttpResponseMessage UpdateWorkflowElement(WorkflowElementModel workflowElementModel)
{
if (!ModelState.IsValid || workflowElementModel == null)
{
return new HttpResponseMessage(HttpStatusCode.BadRequest);
}
var response = new HttpResponseMessage(HttpStatusCode.OK);
string responseMessage;
if (workflowElementModel.RefTime == DateTime.MinValue)
{
workflowElementModel.RefTime = DateTime.UtcNow;
}
var resultMessages = new List<NotificationMessage>();
var instanceId = new Guid();
if (string.IsNullOrWhiteSpace(workflowElementModel.WorkflowInstanceId) ||
string.IsNullOrWhiteSpace(workflowElementModel.ElementName))
{
responseMessage = "WorkflowInstanceId or ElementName are null or empty";
}
else if (!Guid.TryParse(workflowElementModel.WorkflowInstanceId, out instanceId))
{
responseMessage = "WorkflowInstanceId is not a valid Guid";
}
else
{
var element = new WorkflowElementInstance
{
ElementName = workflowElementModel.ElementName,
RefTime = workflowElementModel.RefTime,
SummaryDescription = workflowElementModel.SummaryDescription ?? "",
FullDescription = workflowElementModel.FullDescription ?? ""
};
_webApiBusinessObject.UpdateWorkflowInstanceState(instanceId, element, resultMessages);
responseMessage = "Element Updated";
}
if (NotificationMessage.HasErrors(resultMessages))
{
responseMessage = resultMessages.Find(m => m.Status == MessageSeverity.Error).Message;
}
response.Content = new StringContent(responseMessage);
return response;
}
It does not work in you case for 3 parameters because you are mixing the expression parameter types.
It.IsAny<List<NotificationMessage>>()
in the setup, as apposed to the
IList<NotificationMessage>
in the callback parameters.
That means the setup expression parameters does not match the callback expression parameters so the call back is not going to be called.
Stick with one type so either go with the List<NotificationMessage> for both
You are also creating new instances of the parameters in the method under test, which would be different instance to the ones used in the setup. That is why the call back is not working. To prove it. Use It.IsAny<>() for all the parameters and it should work
mockWebApiBusinessObject
.Setup(m => m.UpdateWorkflowInstanceState(It.IsAny<Guid>(), It.IsAny<WorkflowElementInstance>(), It.IsAny<List<NotificationMessage>>()))
.Callback<Guid, WorkflowElementInstance, List<NotificationMessage>>(
(workflowInstanceId, elementDetails, resultMessages) =>
{
resultMessages.Add(new NotificationMessage("An Error Occured!", MessageSeverity.Error));
});
Or the more generic interface
mockWebApiBusinessObject
.Setup(m => m.UpdateWorkflowInstanceState(It.IsAny<Guid>(), It.IsAny<WorkflowElementInstance>(), It.IsAny<IList<NotificationMessage>>()))
.Callback<Guid, WorkflowElementInstance, IList<NotificationMessage>>(
(workflowInstanceId, elementDetails, resultMessages) =>
{
resultMessages.Add(new NotificationMessage("An Error Occured!", MessageSeverity.Error));
});
You should also take some time and review Moq Quickstart to get a better understanding of how to use the mocking framework.
Please consider updating at minor places in your unit test.
Add before mocking IWebApiBusinessObject object:
List<NotificationMessage> messages = new List<NotificationMessage>();
Additionally, update Callback :
var mock = new Mock<IWebApiBusinessObject>();
mock.
Setup(m => m.UpdateWorkflowInstanceState(It.IsNotNull<Guid>(), It.IsNotNull<WorkflowElementInstance>(),It.IsAny<List<NotificationMessage>>() )).
Callback(() =>
{
messages.Add(new NotificationMessage("error msg", MessageSeverity.Severe));
messages.Add(new NotificationMessage("Ignore Message", MessageSeverity.Normal)); // this is optional... u can remove it if u want.
});
And need to update the source code method UpdateWorkflowElement(WorkflowElementModel model) to
UpdateWorkflowElement(WorkflowElementModel model, List<NotificationMessage> messages);
Consider changes in unit test code calling UpdateWorkflowElement to
var result = controller.UpdateWorkflowElement(workflowElementModel, messages);
If I have understood your UpdateWorkflowInstanceState() method correctly,
then you are using IWebApiBusinessObject to call UpdateWorkflowInstanceState( , , ) method.
When UpdateWorkflowInstanceState( , , ) executes during unit testing, it fires the Callback in your unit test and adds messages in list of NotificationMessage.
I don't need any confirmation before completion of my form. However, in the following Build() method of the FormBuilder class there is a Confirm("Is this your selection?\n{}")*.
public IForm<T> Build()
{
if (!_form._steps.Any((step) => step.Type == StepType.Field))
{
var paths = new List<string>();
FormBuilder<T>.FieldPaths(typeof(T), "", paths);
IFormBuilder<T> builder = this;
foreach (var path in paths)
{
builder.Field(new FieldReflector<T>(path));
}
builder.Confirm("Is this your selection?\n{*}");
}
Validate();
return this._form;
}
Is there any way I can remove this step from my generated Form after calling build ?
var form = new FormBuilder<QuestionYourThinking>()
.OnCompletionAsync(async (context, state) =>
{
await context.PostAsync("L'exercice est maintenant terminé. A bientot !");
})
.Build();
Just use the overload that take an ActiveDelegate parameter and make the method handler to return false then the confirmation message will not be shown.
return new FormBuilder<QuestionYourThinking>()
.AddRemainingFields()
.Confirm("No verification will be shown", state => false)
.Message("L'exercice est maintenant terminé. A bientot !")
.Build();
To send a message you can just use the fluent method Message.
You can just use .AddRemainingFields() on your FormBuilder. It will not ask for any confirmation.
.Confirm should be used when you want to add custom confirmation message for any specific field.
I am new to simple injector. I have data access layer that has dependency on Force Client. I have register the ForceClient dependency. I want to replace the default value of ForceClient once user login into the application.
Please let me know, how i can change the default values at run time.
Ioc.ServiceContainer.Register(() => new ForceClient(
"test",
"test",
"test"));
Here is the complete detail about the requirement. I have DAL in our Xamarin project that retrieve data from sales force using Developerforce.Force apis. I am writing unit test cases using MOQ to test the DAL.
DAL Code.
public CustomerRepository(IForceClient client)
{
_client = client;
}
public async Task<long> GetTotalContacts()
{
string totalContactCountQry = "some query"
var customerCount = await _client.QueryAsync<ContactsTotal>(totalContactCountQry);
var firstOrDefault = customerCount.Records.FirstOrDefault();
return firstOrDefault != null ? firstOrDefault.Total : 0;
}
Unit Test Case Code.
[SetUp]
public void Init()
{
forceClientMock = new Mock<IForceClient>();
forceClientMock.Setup(x => x.ForceClient(It.IsAny<string>(),
It.IsAny<string>(), It.IsAny<string>(), It.IsAny<HttpClient>()))
.Return(new ForceClient(It.IsAny<string>(), It.IsAny<string>(),
It.IsAny<string>(), It.IsAny<HttpClient>()));
forceClientMock.Setup(x => x.QueryAsync<ContactsTotal>(It.IsAny<string>()))
.ReturnsAsync(new QueryResult<ContactsTotal>());
forceClientMock.Setup(x => x.QueryAsync<ContactsTotal>(It.IsAny<string>()))
.ReturnsAsync(new QueryResult<ContactsTotal>() { Records=new List<ContactsTotal>() });
}
[Test]
public void GetTotalContacts()
{
ICustomerRepository customerRepostory = new CustomerRepository(forceClientMock.Object);
Assert.AreEqual(customerRepostory.GetTotalContacts().Result,0);
}
Simple Injector Registry on application initialization
container.Register<IForceClient>((() => new ForceClient(
UserState.Current.ApiBaseUrl,
UserState.Current.AuthToken.AccessToken,
UserState.Current.ApiVersion)), Lifestyle.Transient);
The instance of ForceClient that i am creating during the registry is being created with all default valued of UserState. The actual value gets assigned once user login into the application.
I except ForceClient instance to have the updated value after login to access the sales force to retrieve the data but the program is giving error on below line DAL
var customerCount = await _client.QueryAsync<ContactsTotal>(totalContactCountQry);
The reason is that the forceClient still contain default values. How can i make sure that the FoceClient instance get created after login to use the actual value of UserState
You can accomplish what you want by using Func<T>.
Rather than IForceClient in your classe, you can inject a Func<IForceClient> :
public CustomerRepository(Func<IForceClient> clientFunc)
{
_clientFunc = clientFunc;
}
public async Task<long> GetTotalContacts()
{
string totalContactCountQry = "some query"
// calling _clientFunc() will provide you a new instance of IForceClient
var customerCount = await _clientFunc().QueryAsync<ContactsTotal>(totalContactCountQry);
var firstOrDefault = customerCount.Records.FirstOrDefault();
return firstOrDefault != null ? firstOrDefault.Total : 0;
}
The simple injector registration:
// Your function
Func<IForceClient> fonceClientFunc = () => new ForceClient(
UserState.Current.ApiBaseUrl,
UserState.Current.AuthToken.AccessToken,
UserState.Current.ApiVersion);
// the registration
container.Register<Func<IForceClient>>( () => fonceClientFunc, Lifestyle.Transient);
is it possible to assert whether a method has been called? I'm testing the following method and I want to assert that the _tokenManager.GetToken() has been called. I just want to know if the method has been called as the method does not return a value. I am using Moq.
Thanks,
Code snippet
public void Subscribe(string code, string emailAddress, string columnKey)
{
// Request authentication token
var token = _tokenManager.GetToken(code, false);
if (!_tokenValidator.Validate(token))
{
// Token has expired or invalid - refresh the token
token = _tokenManager.GetToken(code, true);
}
// Subscribe email
_silverpopRepository.Subscribe(token.AccessToken, emailAddress, columnKey);
}
You should mock TokenManager and TokenValidator, and then create two unit test cases:
Case 1: token is validated and GetToken is called exactly once
Case 2: token is not validated and GetToken is called exactly twice
Case 1:
[Test]
public void Subscribe_TokenIsValidated_GetTokenIsCalledOnce()
{
// Arrange:
var tokenManagerMock = Mock.Of<TokenManager>();
var tokenValidatorMock = Mock.Of<TokenValidator>(x =>
x.Validate(It.IsAny<Token>()) == true);
var subscriber = new Subscriber
{
TokenManager = tokenManagerMock,
TokenValidator = tokenValidatorMock
};
// Act:
subscriber.Subscribe(It.IsAny<string>(), It.IsAny<string>(),
It.IsAny<string>());
// Assert:
Mock.Get(tokenManagerMock).Verify(x =>
x.GetToken(It.IsAny<string>(), It.IsAny<bool>()), Times.Once);
}
Case 2:
[Test]
public void Subscribe_TokenIsExpiredOrInvalid_GetTokenIsCalledTwice()
{
// Arrange:
var tokenManagerMock = Mock.Of<TokenManager>();
var tokenValidatorMock = Mock.Of<TokenValidator>(x =>
x.Validate(It.IsAny<Token>()) == false);
var subscriber = new Subscriber
{
TokenManager = tokenManagerMock,
TokenValidator = tokenValidatorMock
};
// Act:
subscriber.Subscribe(It.IsAny<string>(), It.IsAny<string>(),
It.IsAny<string>());
// Assert:
Mock.Get(tokenManagerMock).Verify(x =>
x.GetToken(It.IsAny<string>(), It.IsAny<bool>()), Times.Exactly(2));
}
Alternatively, you can create an unit test without mocking TokenValidator and verify if GetToken() has been called at least once. However, creating two cases as in the first example is preferred as we are testing all code paths.
// Arrange:
var tokenManagerMock = Mock.Of<TokenManager>();
var subscriber = new Subscriber {TokenManager = tokenManagerMock};
// Act:
subscriber.Subscribe(It.IsAny<string>(),
It.IsAny<string>(),
It.IsAny<string>());
// Assert:
Mock.Get(tokenManagerMock).Verify(x =>
x.GetToken(It.IsAny<string>(), It.IsAny<bool>()), Times.AtLeastOnce);
Read more about verification in Moq at:
Moq quick start at official website
Verifying the Number of Calls to a Mocked Method at BlackWasp
You can verify using MOQ using the Verify method. Like this:
var tokenManagerMock = new Mock<ITokenManager>();
var sut = new WhateverItIsCalled(tokenManagerMock.Object);
sut.Subscribe("ssss", "example#example.com", "XXX");
tokenManagerMock.Verify(m => m.GetToken(It.Is<string>(c => c == "ssss", It.Is<bool>(x => x == false)), Times.Once);
You need to be able to pass the token manager into your system under test somehow. Usually via the ctor or maybe a property.
I would suggest you use something like AutoFixture to remove the ugliness that is "ssss" and make things a bit more DRY.
You may need to make the token manager mock return something appropriate too that will pass the validation. Something like this:
var tokenManagerMock = new Mock<ITokenManager>();
tokenManagerMock.Setup(m => m.GetToken(It.Is<string>(x => x == "ssss", It.IsAny<bool>()).Returns("XXXXXX");