Code lens not showing correct number of tests - visual-studio

In the VS 2013, I see number of unit tests for a method.
It works fine if I am calling the method directly from the TestMethod, but if I call sut from a helper/private method, the codelens does not seem to count that test.
I am using private method to pass different parameters to my test method and execute the test. I know I can use xls, csv or db to do that but I just want to do that in the code and make the test count.
Is there a way to make codelens count tests in this scenario?
MyClass.cs
--1/1 passing ( this is fine)
public bool MyMethbod (bool input)
{
return input
}
MyClassTest.cs
[TestMethod]
public void MyMethod_ShuoldReturnTrue
{
var returnValue = new MyClass().MyMethod(true);
Assert.IsTrue(returnValue)
}
MyClass.cs
--0/0 passing ( I am expecting codelens to show 1/1)
public bool MyMethbod (bool input)
{
return input;
}
MyClassTest.cs
[TestMethod]
public void MyMethod_ShuoldReturnTrue
{
MyMethod_ShuoldReturnTrue_Refactored(true);
}
private void MyMethod_ShuoldReturnTrue_Refactored(bool someValue)
{
var returnValue = new MyClass().MyMethod(someValue);
Assert.AreEqual(returnValue, someValue);
}

Related

Can I call a function from the base class which return bool from derived class

I have the following base class:
class node_layer_manager_t : public layer_manager_t
{
protected:
//Devices
trx_t trx;
private:
std::vector<string> trx_dump_labels;
public:
node_layer_manager_t( xml::node_t& params );
~node_layer_manager_t();
virtual bool set_profile(void) override;
}
I created the following derived class:
class node_layer_manager_with_rad_t : public node_layer_manager_t
{
protected:
//Devices
radio_t radio;
public:
node_layer_manager_with_rad_t(xml::node_t& params );
~node_layer_manager_with_rad_t();
virtual bool set_profile(void) override;
virtual void radio_monitoring_job_function(void);
intervalues_t<double> radio_tmp;
ushort duration_seconds_for_radio_monitoring;
};
I want it so that the set profile will execute the set_profile of the base class and in addition some other action.
Can I just write it this way?
bool node_layer_manager_with_rad_t::set_profile(void)
{
bool success;
node_layer_manager_t::set_profile();
try
{
string_t profile_tag = "logs/trx_dump/node:"+get_id();
dev_tx = profile->get_decendant(profile_tag.c_str());
cout<<"sarit id= "<< get_id()<<endl;
success = true;
}
catch(...)
{
cout<<"sarit profile error: "<<endl;
success = false;
}
return success; //**
}
**Or should I reurn the follwing:
return (success && node_layer_manager_t::set_profile());
If you have to call parent set_profile regardless what you have to do in derived class, you should adopt design which take care about this constraint.
Typically, you should mark based class set_porfile as final and manage call of a dedicated derived class method inside based class:
class node_layer_manager_t : public layer_manager_t
{
protected:
....
// set_profile actions of derived class
// proposed a default without side effect implementation if
// derived class doesn't need to overload this.
virtual bool set_profile_child() { return true; };
private:
....
public:
.....
// Manage here call of derived
virtual bool set_profile() override final
{
// actions before derived specific actions
....
// Call specific derived class actions
bool success = set_profile_child();
// actions after derived specific actions
if (success)
{
//do based class action
}
return success;
}
}
and in child:
class node_layer_manager_with_rad_t : public node_layer_manager_t
{
protected:
....
public:
virtual bool set_profile_child() override;
};
// Manage only there own action, regardless of needs of based class
bool node_layer_manager_with_rad_t::set_profile(void)
{
try
{
// Do what you're in charge, and only what you're in charge!
}
catch(...)
{
cout<<"sarit profile error: "<<endl;
success = false;
}
return success; //**
}
With this kind of design, each class do only what it have to manage, and only its. Derived class doesn't have to deal with needs of based class.
If you want to offer to your derived class ability to decided if code is executed before or after generic behavior, you can replace or add to set_profile_child() two methods: bool pre_set_profile() and bool post_set_profile()
At first, you haven't declared success anywhere (so actually, this is not a mcve, the code should not compile as is).
Still I get it - and tThe answer is: it depends on what you actually want to do...
Do you want to call the super class first or after the sub class code? Your example implies the former, your alternative the latter. Do you want to abort if the super class function fails or still execute your code?
Your inital example calls the super class function, ignores the result and does its own stuff afterwards.
This calls the super class function first and continues only on success:
bool success = node_layer_manager_t::set_profile();
if(success)
{
try { /*...*/ } // <- no need to set success to true, it is already
catch(...) { /*...*/ success = false; }
}
This executes both, but combines the result:
bool success = node_layer_manager_t::set_profile();
try { /*...*/ } // <- do not modify success, must remain false if super class failed!
catch(...) { /*...*/ success = false; }
Your alternative hints to executing the sub class code first and only call the super class function, if nothing went wrong.
Any of these approaches might be appropriate, none of them might be. You have to get a clear image of what your requirements are - and then implement the code such that your needs are satisfied...

Console.ReadLine() passed to C# event

I'm learning RX and would like to use Console.ReadLine as a source for observable sequences.
I know that I can create "IEnumerable" using "yield return", but for my concrete use case I've decided to create a C# event, so that potentially many observers will be able to share the same keyboard input.
Here is my code:
class Program
{
private delegate void OnNewInputLineHandler(string line);
private static event OnNewInputLineHandler OnNewInputLineEvent = _ => {};
static void Main(string[] args)
{
Task.Run((Action) GetInput);
var input = ConsoleInput();
input.Subscribe(s=>Console.WriteLine("1: " + s));
Thread.Sleep(30000);
}
private static void GetInput()
{
while (true)
OnNewInputLineEvent(Console.ReadLine());
}
private static IObservable<string> ConsoleInput()
{
return Observable.Create<string>(
(IObserver<string> observer) =>
{
OnNewInputLineHandler h = observer.OnNext;
OnNewInputLineEvent += h;
return Disposable.Create(() => { OnNewInputLineEvent -= h; });
});
}
}
My problem - when I run the GetInput method as it is shown above, the very first input line is not sent to the sequence (but it is sent to the event handler).
However, if I replace it with the following version, everything works as expected:
private static void GetInput()
{
while (true)
{
var s = Console.ReadLine();
OnNewInputLineEvent(s);
}
}
Could someone shed some light on why this might happen?
You're trying to make life difficult for yourself. There is almost always a way to make things simple with Rx. It's just a matter of learning to think more functionally rather than procedurally.
This is all you need:
class Program
{
static void Main(string[] args)
{
var subscription = ConsoleInput().Subscribe(s => Console.WriteLine("1: " + s));
Thread.Sleep(30000);
subscription.Dispose();
}
private static IObservable<string> ConsoleInput()
{
return
Observable
.FromAsync(() => Console.In.ReadLineAsync())
.Repeat()
.Publish()
.RefCount()
.SubscribeOn(Scheduler.Default);
}
}
This lets multiple subscribers share the one input through the .Publish().RefCount(). And the .SubscribeOn(Scheduler.Default) pushes the subscription out to a new thread - without it you block on a subscription.
If you move Task.Run((Action) GetInput); to after the subscription your code will work as desired. This is because in your original version, the first call of OnNewInputEvent(Console.ReadLine()) is run before you've hooked OnNewInputLineEvent to the observer.OnNext.

JFace TreeView not launching when Input is a String

I'm trying launch a simple JFace Tree.
It's acting really strange however. When I setInput() to be a single String, the tree opens up completely blank. However, when I set input to be a String array, it works great.
This has nothing to do with the LabelProvider or ContentProvider since these behave the same no matter what (it's a really simple experimental program).
setInput() is officially allowed to take any Object. I am confused why it will not take a String, and knowing why may help me solve my other problems in life.
Setting a single String as input:
TreeViewer treeViewerLeft = new TreeViewer(shell, SWT.SINGLE);
treeViewerLeft.setLabelProvider(new TestLabelProvider());
treeViewerLeft.setContentProvider(new TestCompareContentProvider());
treeViewerLeft.expandAll();
treeViewerLeft.setInput(new String("Stooge"));
Setting an array of Strings:
TreeViewer treeViewerLeft = new TreeViewer(shell, SWT.SINGLE);
treeViewerLeft.setLabelProvider(new TestLabelProvider());
treeViewerLeft.setContentProvider(new TestCompareContentProvider());
treeViewerLeft.expandAll();
treeViewerLeft.setInput(new String[]{"Moe", "Larry", "Curly"});
The second works, and launches a tree using the following providers:
public class TestCompareContentProvider extends ArrayContentProvider implements ITreeContentProvider {
public static int children = 0;
public Object[] getChildren(Object parentElement) {
children++;
if (children > 20){
return null;
}
return new String[] {"Moe", "Larry", "Curly"};
}
public Object getParent(Object element) {
return "Parent";
}
public boolean hasChildren(Object element) {
if (children >20){
return false;
}
return true;
}
}
and
public class TestLabelProvider extends LabelProvider {
public String getText(Object element){
return "I'm something";
}
public Image getImage(Object element){
return null;
}
}
You've inherited getElements from the ArrayContentProvider and that only works with arrays. You should override this method.
I don't think you need to extend ArrayContentProvider at all.

How To write TestCase nunit test for keyPairValue

I am looking for a way to pass keyValuePair into my test with TestCase
[TestCase<KeyValuePair<int,string>>(1,"XX")]
public void someTest(KeyValuePair<int,string> expectedkeyValuePairs)
{
// do some thing;
}
The answer is
[TestCase(1,"XXX")]
public void someTest(int key,string value)
{
var expectedkeyValuePairs = new KeyValuePair<int, string>(key, value);
// do some thing;
}
Simply use two separate parameters: One for key, one for value. And then create the KeyValuePair from them within your test.

callback / delegate?

i have a doubt..
i would like to create a function and it will look like this...
public class A //this is just a class file
{
function dowork()
{
//work 1
INPUT = here in this line it should call a delegate function or raise event etc...
//work 2 using INPUT
}
}
public class B
{
function myfn()
{
A objA = new A();
objA.dowork();
}
}
In the "Class A" we will raise event or so & it will display a windows form to user and then user will input some value & we need to return that value to Class A -> dowork method.... then only we should continue "work 2"
this should also support multi threading... anyone have idea how we can implement this??
thanks :)
You can use ManulResetEvent for this purpose: You run your input form and when it done that form set the event so you can catch it from A.dowork method. While the input in action you run the infinite loop, check event state and process application event to make you app responsible in this time:
public class A //this is just a class file
{
private ManualResetEvent _event;
public void dowork()
{
//work 1
_event = new ManualResetEvent(false);
//INPUT = here in this ...
Worker worker = new Worker();
worker.DoInput(_event);
while(true)
{
if(_event.WaitOne())
break;
Application.DoEvents();
}
//work 2 using INPUT
}
}
class Worker
{
private ManualResetEvent _event;
public void DoInput(ManualResetEvent #event)
{
_event = #event;
// Show input form here.
// When it done, you call: _event.Set();
}
}
Also, I suggest you (if you can) use Async library (it is available as a standalone setup). There you can implement it in much more straightforward way:
public class A //this is just a class file
{
public async void dowork()
{
//work 1
//INPUT = here in this ...
Worker worker = new Worker();
wait worker.DoInput();
//work 2 using INPUT
}
}
class Worker
{
public async void DoInput()
{
InputForm form = new InputForm();
wait form.ShowInput();
}
}
public class B
{
async void myfn()
{
A objA = new A();
wait objA.dowork();
}
}
As you see you just wait while other piece of code get executed without any UI locking and events.
I can provide deeper explanation of how async/wait works here if you need.

Resources