What I'd like to do is exactly the first example from this page but...
http://nunit.org/index.php?p=testCaseSource&r=2.5
with value that I can change
static object[] DivideCases =
{
for (int i = 0; i < qtyCmd(); i++)
{
new object[] { getCmd[i] },
}
};
qtyCmd is just a static method which return a number
getCmd read a line (index sent as parameter) in a text file
where the arrays command. I know about Data-Driven Unit Test, but I was asked to do not use it. To be more specific, I am asked to do so with [TestCase]
You can turn DivideCases into a method:
private object[] DivideCases() {
var amountOfSamples = qtyCmd();
var result = new object[amountOfSamples];
for (var i = 0; i < amountOfSamples; i++) {
result[i] = new object[] {getCmd[i]};
}
return result;
}
And then use it with TestCaseSource:
[Test, TestCaseSource("DivideCases")]
public void TestMethod(object[] samples) {
// Your test here.
}
Related
I'm using bubble sort for sort a array in descending order and print the output in console.writeline method, now i'm confused how to write a unit test to test against the console.writeline
//Console Application Code
public int PrintData(int[] input, int n)
{
for (int i = 0; i < n; i++)
{
if (input[i] <= 0)
{
status = -2;
}
else
{
for (int j = i + 1; j < n; j++)
{
if (input[i] < input[j])
{
int temp = input[i];
input[i] = input[j];
input[j] = temp;
}
}
}
}
for (int i = 0; i < n; i++)
{
Console.WriteLine(input[i]); //How to check this output in MSTest
}
}
//MS Test Code
[TestMethod]
public void ArrayDisplayingInDescendingOrder()
{
int[] arr = new int[5] { 3, 2, 1, 4, 5 };
int[] expected = { 5, 4, 3, 2, 1 };
array.PrintData(arr, 5);
//What i should do here
}
If you really want to test the Concole.WriteLine calls I would create a class with an interface to encapsulate the Console.WriteLine. Could look like this.
public class ConsoleService : IConsoleService
{
public void WriteToConsole(string text)
{
Console.WriteLine(text);
}
}
Then you can use this service in your PrintData method and mock the calls in your test and verify the calls; for example with Moq.
Easier would be to return a List from PrintData and add each entry to the list instead of Console.WriteLine(input[i]); because then you can test if the correct values where added. And in your application you simply can print all entries with a for each loop.
So you have to change your code to make it testable. But your code would be cleaner after this (I would hardly recommend not to use any UI interaction in logic classes). Good example on how tests can make code cleaner, too ;)
You could add a TextWriter argument to your method and use this one to write:
public int PrintData(int[] input, int n, TextWriter sw)
{
...
sw.WriteLine(input[i]);
}
When you call the method, you could then supply any TextWriter, including Console.Out or a stub:
PrintData(new int[0], 0, Console.Out); //writes to the console
//in unit test:
TextWriter tw = new StringWriter();
PrintData(new int[0], 0, tw); //writes to tw
Assert.AreEqual("...", tw.ToString());
I have figured out most (I think) of the values for PID and RAX using NHapi for hl7 2.5.1.
What I am having difficulties on are the ones that (I am assuming) use components such as rxa.AdministeredCode.Components[5].
How do I set that value?
I assume same thing for rxa.GetSubstanceManufacturerName(0).Components? and
rxa.GetAdministrationNotes(0).
Gina
Try this
class Program
{
static void Main(string[] args)
{
EncodingCharacters enchars = new EncodingCharacters('|', "^~\\&");
IModelClassFactory theFactory = new DefaultModelClassFactory();
NHapi.Model.V251.Segment.RXA rxa = new NHapi.Model.V251.Segment.RXA(new VXU_V04(theFactory), theFactory);
IType[] t = rxa.GetSubstanceManufacturerName(0).Components;
SetRXA(t);
Debug.Print(PipeParser.Encode(rxa, enchars));
Console.Read();
}
public static void SetRXA(IType[] components)
{
for (int i = 0; i < components.Length; i++)
{
if (components[i] is IPrimitive)
{
IPrimitive prim = (IPrimitive)components[i];
prim.Value = "Component"+i;
}
else if (components[i] is IComposite)
SetRXA(((IComposite)components[i]).Components);
//if Varies do something else
}
}
}
Leaving the performance cost of LINQ usage, I would like to know how to convert the following code into a LINQ expression
for (int i = 0; i < someArray.length(); i++)
yield return new SomeEntity(someFunction(i));
Important: I need the use of the incremented index
Update:
Rather than someArray.length(), number should be used:
for (int i = 0; i < number; i++)
yield return new SomeEntity(someFunction(i));
2nd update
I'm still getting the compilation error "not all code paths return value"
My code:
public static IEnumerable function()
{
Enumerable.Range(0,5).Select(i => new Entity());
}
3rd update
Didn't think it's relevant until I found out it's the cause for this error..
public static IEnumerable function()
{
int[] arr = { 1, 2, 3, 4 };
foreach (int i in arr)
{
Enumerable.Range(0,5).Select(i => new Entity());
}
}
If you take out the foreach 1st loop out of the equation, all replies answer to this question, but my issue is n^2.. 2 nested loops...
Any ideas?
Use the overload of Enumerable.Select that has an index into the collection:
someArray.Select((x, i) => new SomeEntity(someFunction(i)));
Edit
As you've modified your example and are not actually using a collection to iterate and index to, use Enumerable.Range:
Enumerable.Range(0, number).Select(i => new SomeEntity(someFunction(i)));
Use Enumerable.Range to generate the numbers:
Enumerable.Range(0,number).Select(i=>new SomeEntity(someFunction(i)));
Here's my LinqPad snippet.
void Main()
{
var e = SomeEntity.GetEntities(new List<int> { 1, 2, 3});
e.Dump();
}
public class SomeEntity
{
public int m_i;
public SomeEntity(int i)
{
m_i = i;
}
public override string ToString()
{
return m_i.ToString();
}
public static int someFunction(int i){ return i+100;}
public static IEnumerable<SomeEntity> GetEntities(IEnumerable<int> someArray)
{
// for (int i = 0; i < someArray.Count();i++)
// yield return new SomeEntity(someFunction(i));
// *** Equivalent linq function ***
return someArray.Select(a => new SomeEntity(someFunction(a)));
}
}
I'm testing the performance of some similar method calls that I'm wrapping in some timing and logging statements. I'm passing these methods in via an Action delegate parameter.
Is there any way to print details about the call?
For example:
var httpResult = TestService(() => serviceHttp.Search(criteria));
var tcpResult = TestService(() => serviceTcp.Search(criteria));
var localResult = TestService(() => servicelocal.Search(criteria));
...
private static double TestService(Action serviceOperation)
{
const int iterations = 15;
...
for (var i = 0; i < iterations; i++)
{
var watch = Stopwatch.StartNew();
...
Console.WriteLine(string.Format("{0} ElapsedMilliseconds={1}", ????, watch.ElapsedMilliseconds));
// Ideally this would print something like "serviceTcp.DoStuff(...) ElapsedMilliseconds=313"
}
...
}
Change your testing method declaration to
private static double TestService(Expression<Action> expression)
Call Compile method of expression object to get a method for testing:
var serviceOperation = expression.Compile();
Expression object can provide a lot of information about method call, you can start with something like this:
private static string GetMethodCallDescription(Expression<Action> expression)
{
var mce = (MethodCallExpression)expression.Body;
var method = mce.Method;
var sb = new StringBuilder();
sb.Append(method.DeclaringType.Name);
sb.Append(".");
sb.Append(method.Name);
sb.Append("(");
bool firstarg = true;
foreach(var arg in mce.Arguments)
{
if(!firstarg)
{
sb.Append(", ");
}
else
{
firstarg = false;
}
sb.Append(arg.ToString());
}
sb.Append(")");
return sb.ToString();
}
You could do it without using expression trees; just change the signature of TestService to take the action and the parameter separately, and use the Delegate.Target and Delegate.Method properties to get the type and method:
var httpResult = TestService(serviceHttp.Search, criteria);
var tcpResult = TestService(serviceTcp.Search, criteria);
var localResult = TestService(servicelocal.Search, criteria);
...
private static double TestService<T>(Action<T> serviceOperation, T parameter)
{
const int iterations = 15;
...
for (var i = 0; i < iterations; i++)
{
var watch = Stopwatch.StartNew();
...
string typeName = serviceOperation.Method.IsStatic
? serviceOperation.Method.DeclaringType.Name
: serviceOperation.Target.GetType().Name;
string methodName = serviceOperation.Method.Name;
Console.WriteLine(string.Format("{0}.{1} ElapsedMilliseconds={2}", typeName, methodName, watch.ElapsedMilliseconds));
// Ideally this would print something like "serviceTcp.DoStuff(...) ElapsedMilliseconds=313"
}
...
}
In the following program, DummyMethod always print 5. But if we use the commented code instead, we get different values (i.e. 1, 2, 3, 4). Can anybody please explain why this is happenning?
delegate int Methodx(object obj);
static int DummyMethod(int i)
{
Console.WriteLine("In DummyMethod method i = " + i);
return i + 10;
}
static void Main(string[] args)
{
List<Methodx> methods = new List<Methodx>();
for (int i = 0; i < 5; ++i)
{
methods.Add(delegate(object obj) { return DummyMethod(i); });
}
//methods.Add(delegate(object obj) { return DummyMethod(1); });
//methods.Add(delegate(object obj) { return DummyMethod(2); });
//methods.Add(delegate(object obj) { return DummyMethod(3); });
//methods.Add(delegate(object obj) { return DummyMethod(4); });
foreach (var method in methods)
{
int c = method(null);
Console.WriteLine("In main method c = " + c);
}
}
Also if the following code is used, I get the desired result.
for (int i = 0; i < 5; ++i)
{
int j = i;
methods.Add(delegate(object obj) { return DummyMethod(j); });
}
The problem is that you're capturing the same variable i in every delegate - which by the end of the loop just has the value 5.
Instead, you want each delegate to capture a different variable, which means declaring a new variable in the loop:
for (int i = 0; i < 5; ++i)
{
int localCopy = i;
methods.Add(delegate(object obj) { return DummyMethod(localCopy); });
}
This is a pretty common "gotcha" - you can read a bit more about captured variables and closures in my closures article.
This article will probably help you understand what is happening (i.e. what a closure is): http://blogs.msdn.com/oldnewthing/archive/2006/08/02/686456.aspx
If you look at the code generated (using Reflector) you can see the difference:
private static void Method2()
{
List<Methodx> list = new List<Methodx>();
Methodx item = null;
<>c__DisplayClassa classa = new <>c__DisplayClassa();
classa.i = 0;
while (classa.i < 5)
{
if (item == null)
{
item = new Methodx(classa.<Method2>b__8);
}
list.Add(item);
classa.i++;
}
foreach (Methodx methodx2 in list)
{
Console.WriteLine("In main method c = " + methodx2(null));
}
}
When you use the initial code it creates a temporary class in the background, this class holds a reference to the "i" variable, so as per Jon's answer, you only see the final value of this.
private sealed class <>c__DisplayClassa
{
// Fields
public int i;
// Methods
public <>c__DisplayClassa();
public int <Method2>b__8(object obj);
}
I really recommend looking at the code in Reflector to see what's going on, its how I made sense of captured variables. Make sure you set the Optimization of the code to ".NET 1.0" in the Option menu, otherwise it'll hide all the behind scenes stuff.
I think it is because the variable i is put to the heap (it's a captured variable)
Take a look at this answer.