How do I generate unit test for the following method within VS2010 ?
public bool myResult(Func<int, int, bool> myFunc)
{
int a = 1;
int b = 2;
return myFunc(a, b);
}
When I right-click and select "Generate Unit Tests..." the myResult method is not available to select for a unit test. Methods that do not contain Func as parameters do appear.
While the automatic test generator doesn't work, you can just make the unit test manually.
All that is required is to have a method that's flagged with [TestMethod] in your class, and write the unit test(s) yourself.
Related
please consider the below code,
class A {
foo() {
int a = logicToGetA();
int _bar() => someOtherLogic(a);
// ..
int b = _bar();
// ..
}
}
class B {
int _bar(int a) => someOtherLogic(a);
foo() {
int a = logicToGetA();
// ..
int b = _bar(a);
// ..
}
}
main() {
for (int i = 0; i < 1000000; i++) {
A().foo();
}
for (int i = 0; i < 1000000; i++) {
B().foo();
}
}
Explanation: class A has bar() nested inside foo() but class B has bar() outside of foo(). in the second case, bar() can be made as a static method as well.
My Doubt: which way is more efficient, if foo() is called multiple times? If A().foo() is called 1000000 times, will A.foo.bar is redefined that many times?
It depends.
If the _bar function can be defined outside of the foo method, then we can presume that it doesn't reference any local variables of the foo method.
In that case, the compiler can optimize the local function to be just as efficient as the instance method. Maybe it does, maybe it doesn't, so let's check.
See: https://dartpad.dev/4a53a91bf4e0006e4af4c8a598b68ee6 .
This is (attempted) written so that the compiler can't optimize away the invocation of _someOtherLogic.
I also tried making the invocation be to a static method (but then having to pass the object itself as argument to give access to the instance getter for flag).
Running this in dartpad gives me a final set of results of
A: 918460 /ms
B: 798960 /ms
S: 918380 /ms
It seems dart2js is more efficient with the local function than with the instance method.
Running the same code on the VM gives a benchmark result of:
A: 625960.0 /ms
B: 723245.0 /ms
S: 625075.0 /ms
showing that it's performance characteristics are exactly the opposite of dart2js.
It's very likely that dart2js inlines the _bar function when it's statically known. The dart2js compiler tend to be more aggressive about inlining than the VM.
All in all, I wouldn't start to worry about this difference unless the function call shows up heavily in the performance profile of a real-world program.
If your program's performance really depends critically on this one function call, I'd probably inline the function. If not, write whatever is more readable and maintainable, and don't start micro-optimizing until you know it matters.
I am trying to fast forward time to do some tests for a custom runtime module. I have looked at the answer from this thread and followed the answer to use Timestamp, however, I am unable to access the set_timestamp method.
setup:
#[cfg(test)]
mod tests {
use super::*;
use support::dispatch::Vec;
use runtime_primitives::traits::{Hash};
use runtime_io::with_externalities;
use primitives::{H256, Blake2Hasher};
use timestamp;
use support::{impl_outer_origin, assert_ok, assert_noop};
use runtime_primitives::{
BuildStorage,
traits::{BlakeTwo256, IdentityLookup},
testing::{Digest, DigestItem, Header}
};
impl_outer_origin! {
pub enum Origin for Test {}
}
#[derive(Clone, Eq, PartialEq)]
pub struct Test;
impl system::Trait for Test {
type Origin = Origin;
type Index = u64;
type BlockNumber = u64;
type Hash = H256;
type Hashing = BlakeTwo256;
type Digest = Digest;
type AccountId = u64;
type Lookup = IdentityLookup<Self::AccountId>;
type Header = Header;
type Event = ();
type Log = DigestItem;
}
impl super::Trait for Test {
type Event = ();
}
impl timestamp::Trait for Test {
type Moment = u64;
type OnTimestampSet = ();
}
type Pizza = Module<Test>;
And the error is below:
error[E0599]: no function or associated item named `set_timestamp` found for type
`srml_timestamp::Module<tests::Test>` in the current scope
|
254 | let now = <timestamp::Module<tests::Test>>::set_timestamp(9);
| ^^^^^^^^^^^^^ function or associated item
not found in `srml_timestamp::Module<tests::Test>`
In Substrate v1.0, the set_timestamp function has a #[cfg(feature = "std")] attribute on it:
https://github.com/paritytech/substrate/blob/v1.0/srml/timestamp/src/lib.rs#L276
This means it will only be visible if you are compiling with std. When you write tests, this should work, but I assume that this issue is appearing because you are trying to call it from within the runtime environment, which much be no_std.
If for some reason you do need to modify the timestamp from within your runtime, you should be able to do so directly:
https://github.com/paritytech/substrate/blob/v1.0/srml/timestamp/src/lib.rs#L249
<timestamp::Module<T>>::Now::put(new_time)
(I haven't tested this, but something like it should work).
Let me know if this helps.
In Substrate v1.0 you can declare
type Moment = timestamp::Module<Test>;
Then use it to set a specific timestamp.
Moment::set_timestamp(9);
If you want to get the timestamp value, you can do:
let now_timestamp = Moment::now();
I would like to use a breakpoint to execute code in Visual Studio 2017 and have the side effects of that code affect the program. It appears from Execute code when breakpoint is hit? that this was possible in a past version of Visual Studio.
But consider the code below.
int Counter = 0;
public bool Increment()
{
Counter++;
return false;
}
public void PrintNumbers()
{
for (int i = 0; i < 3; i++)
{
Debug.WriteLine($"Iteration {i}");
}
Debug.WriteLine("Counter: " + Counter);
}
I have set a breakpoint on the line that runs the "Iteration" as follows:
When this runs, it produces the following output:
Iteration 0
Iteration 1
Iteration 2
Counter: 0
This is a true technological marvel! Visual Studio does run the code -- if I change the "return false" in Increment() to "return true," the breakpoint will be hit. But it magically avoids side effects. That's great! But I want side effects. In other words, I really want an action option besides "log a message to output windows" that allows execution of code with side effects. Is there any way around this Visual Studio feature?
You might be wondering why I want to do this. I would like to make a conditional breakpoint dependent on another conditional breakpoint having been passed. (For example, I know that the Knight is talking funny after meeting the Princess, so I want to put a breakpoint on KnightTalks() that stops only if some code in KnightMeetsPrincess() has executed. I run into situations this all the time and get annoyed when I have to disable the KnightTalks breakpoint and reenable it after KnightMeetsPrincess, especially when there is a longer chain of events.) Based on Conditional breakpoint depends on other breakpoint, I think there is no built-in way to do this. But I could do something like it if I could execute arbitrary code -- for example, if I could set and get a pseudovariable. Or one could use code like the following:
public static class Bookmark
{
static Dictionary<string, int> HitCounts = new Dictionary<string, int>();
public static bool Set(string s)
{
if (!HitCounts.ContainsKey(s))
HitCounts[s] = 1;
else
HitCounts[s]++;
return false;
}
public static bool Set(string s, bool condition)
{
if (condition)
Set(s);
return false;
}
public static bool Get(string s)
{
return HitCounts.ContainsKey(s);
}
}
The idea of this code was that I would put a conditional breakpoint on KnightMeetsPrincess that called Bookmark.Set("KnightMeetsPrincess") and then on KnightTalks, a separate conditional breakpoint called Bookmark.Get("KnightMeetsPrincess"). Alas, this doesn't work because the code executes, but without side effects.
Any workarounds?
The F# compiler gives an error saying I must add a project reference because the type I'm using has a method argument that lives in that project. But this method is private!
I have the following project structure:
Program -> Library -> SubLibrary
SubLibrary contains this:
namespace SubLibrary
type Widget = { Value: int }
Library contains this:
namespace Library
open SubLibrary
type Banana =
{ Value: int }
member private x.TakeWidget (w: Widget) = ()
Program contains this:
open Library
[<EntryPoint>]
let main argv =
printfn "%A" argv
let banana = { Value = 42 }
0
I get this error:
error FS0074:
The type referenced through 'SubLibrary.Widget' is defined in an assembly that is not referenced.
You must add a reference to assembly 'SubLibrary'
But the TakeWidget method is private!
I tried changing Banana into a class, rather than a record, but that made no difference.
As an experiment, I created a C# version of Library, called CLibrary:
using SubLibrary;
namespace CLibrary {
public class CBanana {
int m_value;
public CBanana(int value) {
m_value = value;
}
private void TakeWidget(Widget w) {
}
}
}
Then I changed Program to use CBanana instead of Banana:
open Library
[<EntryPoint>]
let main argv =
printfn "%A" argv
let banana = CBanana 42
0
Now I don't get an error. In fact, with C# I can make that method public, and so long as I don't try to compile a call to it, there is no error.
Why is the compiler insisting I add a reference to SubLibrary? Sure, I could just go ahead and do what it tells me to do, for a quiet life, but SubLibrary is a private implementation detail of Library, which should not be exposed to Program.
Actually, when I tried with a class instead of record, it did the trick (F# 3.1):
type BananaClass (value:int) =
member private x.TakeWidget (w: Widget) = ()
member x.Value = value
You can work around it with a record as well - you need to move the private member into a separate module and have it as a type augmentation:
type Banana = { Value: int }
module Ext =
type Banana with
member x.TakeWidget (w: Widget) = ()
Compiler won't complain about the missing dependency until you open the Ext module.
I don't have a good idea why the compiler was complaining in the first place. Probably one of its quirks. I couldn't find anything seriously suspicious in the generated IL (other than a surprising fact that F# compiler marks both private and internal members as internal in the IL - this turned out to be of no consequence here).
Indeed this to me looks like an error I have raised an issue here, https://github.com/Microsoft/visualfsharp/issues/86. So you'll be able to track feedback from there.
Say i have a method which populate some data to a list and it internally calls one more method(which i'm testing independently) and that populate some data to the list. Here what is the best way of testing?
How to test the outer Method? Should I check for the data's from inner Method also, else it is ok to test only the data's populated by outer method?
Given the following class under test:
class MyTestClass {
int getAPlusB() { return getA() + getB() }
int getA() { return 1 }
int getB() { return 2 }
}
I can write the following spock test to check that the arithmetic is correct, but also that getA() and getB() are actually called by getAPlusB():
def "test using all methods"() {
given: MyTestClass thing = Spy(MyTestClass)
when: def answer = thing.getAPlusB()
then: 1 * thing.getA()
1 * thing.getB()
answer == 3
}
So far this is running all the code on all 3 methods - getA and getB are verified as being called but the code in those methods are actually being executed. In your case, you are testing the inner methods seperately, and perhapse you do not want to call them at all during this test. By using the spock spy, you can instantiate a real instance of the class under test, but with the option of stubbing particular methods which you want to specify the value returned by:
def "test which stubs getA and getB"() {
given: MyTestClass thing = Spy(MyTestClass)
when: def answer = thing.getAPlusB()
then: 1 * thing.getA() >> 5
1 * thing.getB() >> 2
answer == 7
}