I have a public variable in one View Model that I want to be able to access (get and set) from another Views code-behind. I have a MainWindowViewModel and a SettingsViewModel. The code-behind I want to be able to access this variable already has a DataContext definition for MainWindowViewModel, which I think may be the problem, since as far as I know I cant define two DataContext for the same view.
As an example, SettingsViewModel has a variable called LowerLimit which I have bound to the selected value of a NumericUpDown. I initialized a variable to hold the DataContext as SettingsViewModel so I can access the variable in that ViewModel. I did this with the code
var settingsContext = DataContext as SettingsViewModel;
But for some reason this throwing a NullRefereceException, saying settingsContext is null.
SettingsViewModel.cs:
public double[] LowerLimit { get; set; } = { 0, 0, 0, 0 }; //LowerLimit NumericUpDown
MainWindow.xaml.cs:
public MainWindow()
{
InitializeComponent();
DataContext = new MainWindowViewModel();
}
private void Run_Clicked(object sender, RoutedEventArgs args) //Button click event
{
...
var settingsContext = DataContext as SettingsViewModel;
lowerLimitCol = (int)settingsContext.LowerLimit[generalIndex];
}
I have only provided the relevant code to the problem. If I am mistaken and more code is required to answer the question then I can provide it.
Expected result: settingsContext gets DataContext from SettingsViewModel, allowing me to access the LowerLimit variable from MainWindow.xaml.cs and assign it to a local variable.
Actual result: NullReferenceException, settingsContext was null
You are initializing your DataContext to an instance of MainWindowViewModel:
DataContext = new MainWindowViewModel();
And then you're trying to cast DataContext to SettingsViewModel:
var settingsContext = DataContext as SettingsViewModel;
This obviously won't work because you set DataContext to an instance of MainWindowViewModel and not SettingsViewModel.
One way around this would be to expose your SettingsViewModel as a property of MainWindowViewModel so you could then do:
var settingsContext = ((MainWindowViewModel)DataContext).Settings
Related
I have the init code and it returns me a structure
public any function init() {
httpService = new http();
httpService.setUrl("#Application.baseURL#security/oauth2/token");
httpService.setMethod("POST");
httpService.addParam(type="header", name="Content-Type", value="application/x-www-form-urlencoded");
httpService.addParam(type="body", value="client_id=#application.clientID#&client_secret=#application.clientsecretID#&grant_type=#application.grant_type#");
result = httpService.send().getPrefix();
return this;
}
problem how can i use the token returned by the method in other methods, if i dump the init, i am just getting the functions, how can i use the data returned by the http
just not getting in my head, because the token is alive for 3600
Thanks
As James says, you should store the result of the http call as an instance variable. Here's one way of doing it using a property and specifying accessors=true for the component so that you can call setHttpResult() and getHttpResult() without having to write those methods. using the variables scope which will make it available to other methods within the component, but not outside.
/* Test.cfc */
component name="test"{
property name="httpResult" type="struct";
public any function init(){
//use "var" to ensure the variable is local to the function only
var httpService = new http();
httpService.setUrl("#Application.baseURL#security/oauth2/token");
httpService.setMethod("POST");
httpService.addParam(type="header", name="Content-Type", value="application/x-www-form-urlencoded");
httpService.addParam(type="body", value="client_id=#application.clientID#&client_secret=#application.clientsecretID#&grant_type=#application.grant_type#");
//store the result privately in the instance
variables.httpResult = httpService.send().getPrefix();
return this;
}
public void function someOtherMethod(){
// this method can access the result struct
var returnedContent = variables.httpResult.fileContent;
}
}
You can then use getHttpResult() inside or outside your component. For example from an external script:
test = New test(); // calls the init() method
WriteDump( test.getHttpResult() ); //auto-generated "getter"
I'm trying to get a mocked object property. During the initialization, 'child' class is getting a reference to a parent's private function. I'd like to catch this reference during testing to check parent's private method.
This is a simplified example of much more complex code:
class Monkey{
final name;
final Perk _perk;
Monkey('Maya', this._perk){
this._perk.jump = this._jump;
}
void _jump(int a){ // here's the problem, not able to test private method
print('jump ${a}');
}
}
All I want to do is to be able to test private method _jump during testing in mockito. I don't want to change the code.
During test I created
class MockPerk extends Mock implements Perk{}
Monkey(mockedPerk);
What I want to achieve is:
Create Monkey instance with mockedPerk
Capture property _perk.jump in MockedPerk class
Get reference to private _jump method of Moneky's class to be able to test it.
Limitation
Making method public is not an option.
Making method public with #visibleForTesting is not an option
You can capture values passed to setters with verify(mock.setter = captureAny). For example:
var mockedPerk = MockPerk();
var monkey = Monkey('Maya', mockedPerk);
var jump = verify(mockedPerk.jump = captureAny).captured.single as void
Function(int);
jump(5); // Prints: jump 5
I am attempting to Unit Test a method that uses Automapper ProjectTo and I'm not sure how to register the mappings in MVC Core. I am using the built in unit testing.
The following is my unit test.
[TestClass]
public class BusinessGenderServiceTest
{
[ClassInitialize]
public static void Init(TestContext context)
{
}
[TestMethod]
public void GetTest()
{
var options = new DbContextOptionsBuilder<GotNextDbContext>()
.UseInMemoryDatabase(databaseName: "GetTest")
.Options;
using (var context = new GotNextDbContext(options))
{
context.GenderLanguage.Add(new GenderLanguage { Id = 1, Name = "Male", Language = 1 });
context.GenderLanguage.Add(new GenderLanguage { Id = 2, Name = "Female", Language = 1 });
context.GenderLanguage.Add(new GenderLanguage { Id = 3, Name = "Hombre", Language = 2 });
context.GenderLanguage.Add(new GenderLanguage { Id = 4, Name = "Hombre", Language = 2 });
context.SaveChanges();
}
using (var context = new GotNextDbContext(options))
{
var service = new GenderService(context);
var result = service.Get(1);
Assert.AreEqual(2, result.Count());
}
}
}
I am getting the following error when I run the test:
Message: Test method GotNext.Test.BusinessGenderServiceTest.GetTest threw exception:
System.InvalidOperationException: Mapper not initialized. Call Initialize with appropriate configuration. If you are trying to use mapper instances through a container or otherwise, make sure you do not have any calls to the static Mapper.Map methods, and if you're using ProjectTo or UseAsDataSource extension methods, make sure you pass in the appropriate IConfigurationProvider instance.
I was able to solve this problem by configuring and initializing automapper in the Init method of each test class.
For example
[ClassInitialize]
public static void Init(TestContext testContext)
{
var mappings = new MapperConfigurationExpression();
mappings.AddProfile<LocationProfile>();
mappings.AddProfile<CompanyProfile>();
Mapper.Initialize(mappings);
}
You can configure AutoMapper in class like this:
public static class AutoMapperConfig
{
public static IMapper Initialize()
{
return new MapperConfiguration((cfg =>
{
cfg.CreateMap<User, UserDto>();
})).CreateMapper();
}
}
And next use it in startup.cs ConfigureService method
services.AddSingleton(AutoMapperConfig.Initialize());
Create a class or classes that configure AutoMapper and instantiate (and call methods, if applicable) in the Startup class.
I got this same error ("System.InvalidOperationException: Mapper not initialized. Call Initialize with appropriate configuration. ...") when I inadvertently / mindlessly switched between AutoMapper's Instance API (which I did have configured) and AutoMapper's Static API (which I did NOT have configured).
Looking closely at the line of code flagged in the error message, I realized I used upper-case 'M' Mapper.Map() instead of my instance member lower-case 'm' mapper.Map().
I am currently having issues with testing a method which my controller uses which is mocked. it has a return type of an specific enum. I am currently always getting back from this mocked method the default enum value, not the value that I have specified it to return. Am i missing something? I have tried both Moq and JustMock lite with the same results. JustMock lite example below.
Hopefully i haven't made any mistakes in copying the code, I have changed all the names of the objects so apologies for that.
Here is part the unit test:
var returnStatus = ExampleEnum.Invalid;
//Mock the client
var client = Mock.Create<ITestInterface>();
Mock.Arrange(() => client.ValidateSomething(Guid.NewGuid()))
.Returns(returnStatus).MustBeCalled();
var testController = new TestController(client);
var result = testController.DoSomething(Guid.NewGuid().ToString()) as ViewResult;
Here are the relevant bits from the controller:
private ITestInterface _client { get; set; }
public TestController(ITestInterface client)
{
_client = client;
}
Here is part of my controller action:
public ActionResult DoSomething(string id)
{
Guid token;
if(!string.IsNullOrEmpty(id) && Guid.TryParse(id, out token))
{
using (var client = _client)
{
ApplicationUser applicationUser;
var status = client.ValidateSomething(token);
switch (status)
{
The client is mocked correctly but the "status" property getting returned is always ExampleEnum.DefaultValue not the value i have specified to be the result.
I hope i have provided enough information. Any help much appreciated.
You probably did your setup wrong.
Guid.NewGuid() returns a new random GUID, so the GUID you use to setup your mock and the GUID you use to call the DoSomething method will never be the same.
You should do something like:
var guid = Guid.NewGuid()
...
Mock.Arrange(() => client.ValidateSomething(guid))
.Returns(returnStatus).MustBeCalled();
...
var result = testController.DoSomething(guid.ToString()) as ViewResult;
using the same GUID for the mock and for the call to DoSomething.
I don't know about JustMock, but with Moq you could also simply use It.IsAny to match all GUIDs:
client.Setup(c => c.ValidateSomething(It.IsAny<Guid>())).Returns(returnStatus);
How do I create unit test with context based on integration component?
I have identified problem as the Extension is trying to resolve implementation and returning error message:
"Object reference not set to an instance of an object."
My class:
public sealed class GetListOfServiceIdsToProcess
{
public InOutArgument<IArguments> Arguments { get; set; }
protected override void Execute(CodeActivityContext context)
{
// I am recieving my error exception here
context.GetExtension<lib.Extension.MyExtenstion>();
var targetIds= (List<int>)Settings.Get("targetIds");
var wfa = this.Arguments.Get(context);
wfa.ListTargetIds = targetIds;
Arguments.Set(context, wfa);
}
}
My Test so far:
I have problem with implementation of the test as far i could get it:
/// <summary>
///A test for Execute
///</summary>
[TestMethod()]
public void ExecuteTest()
{
// create Isettings mock to return collection of service ids
var expected = new List<int>() { 30, 20 };
var wfaInput = new TestWorkFlow();
var serviceIdList = new GetListOfServiceIdsToProcess();
var wfParam = new Dictionary<string, object>();
wfParam.Add("WorkFlowArguments", wfaInput);
var results = WorkflowInvoker.Invoke(serviceIdList, wfParam);
var wfaResult = (IWorkFlowArguments)results["WorkFlowArguments"];
Assert.AreEqual(expected, wfaResult.ListOfServiceIdsToProcess);
}
Instead of using the static WorkflowInvoker.Invoke() new up a WorkflowInvoker instance and add a mock, or whatever is needed for your test, lib.Extension.MyExtenstion to the Extensions collection.
[TestMethod]
public void ExecuteTest()
{
// ...
var invoker = new WorkflowInvoker(activityToTest);
// This way your extension will be available during execution
invoker.Extensions.Add(new MyExtension());
var results = invoker.Invoke(inputArgs);
// ....
}
I have run through multiple options and the problem what I have is MS Workflow.
I have extracted all logic away from workflow code activity into separate class and this class has been put under tests.
This is the best I could do for this. As I have base classes, that are injected, but I could not easily implement what I needed.
Thank you all for help anyway.