I am writing a test application to test an Operation Contract in the a service
Test client:
here is how I am making a call from my test to get the returned bool value
bool operateResult = TestContext.ServiceOperator.Operate(ref Inputmessage);
Service:
The operate method above calls another method
bool Operate(){
OperatorProcess(msg, interface);
}
private bool OperatorProcess(ref Message MessageData, string SendInterface)
{
parse(message);
validate(message);
Transfer(message);
}
From my test my goal is to test the operator method but in the process operator I don't want to
reach the Transfer(message) I want it to exit right after validate and get the result.
How can I programmatically modify it from my test application? Thanks
Note : the transfer method send the parsed and validated method to another service and I want to stop it from sending my request to that service.
Why don't you try extending the class that contains the OperationProcess function and overriding the function then calling your overridden function that only does the few parts you care about... You can keep the parts in your function that you care about and only the functionality you need to test for.
C# examples on how to override
You can declare a global boolean variable test then set it to true during testing and set it to false during production, then you method will look similar to
private bool OperatorProcess(ref Message MessageData, string SendInterface)
{
parse(message);
validate(message);
if(!TEST) Transfer(message);
}
Alternatively, if you don't want to create a global variable, then you can just add a parameter to the method signature
private bool OperatorProcess(ref Message MessageData, string SendInterface, bool performTransfer)
{
parse(message);
validate(message);
if(performTransfer) Transfer(message);
}
Related
I have been trying to mock a function that included optional parameters with fixed parameters but every time I am getting a null value
here is my function defined in interface which I want to mock:
List<object> GetEntitiesByIDs(List<long> ids, bool includeStatuses = false, bool includeRounds = false, bool includeSample = false);
Method calling this function:
public object ExportSpecimens(List<long> ids)
{
var specimens = Repo.GetEntitiesByIDs(ids, includeSample: true);
}
Here is my test method:
public void ExportSpecimens_ValidData_Success()
{
var _repo = Substitute.For<IRepo>();
_repo.GetEntitiesByIDs(Arg.Any<List<long>>(), includeSample: Arg.Any<bool>()).Returns(_specimens);
}
whenever I am hitting the function in ExportSpecimens I am getting null value.
I also tried to include all the parameters in both the test and main function but it didn't work.
but I have noticed some ambiguity after hitting the function GetEntitiesByIDs first time in ExportSpecimens I am getting null value and then I hit it again by scrolling up the debugger point or in immediate windows I am getting correct input.
I am not able to understand how can I mock this function without any issue?
I am not able to find anything in which I can have a better understanding of the solution to my question. However, for now, to move my work forward I have come to a workaround in which I have created an overloaded function with the fixed parameters which I am able to mock successfully.
For example:
I want to mock this function:
List<object> GetEntitiesByIDs(List<long> ids, bool includeStatuses = false, bool includeRounds = false, bool includeSample = false);
Instead of directly mocking it I have created an another function which calling this main function:
List<object> GetEntitiesByIDs(bool includeSample, List<long> ids){
GetEntitiesByIDs(ids, includeSample: includeSample)
}
and it worked like a charm!
I am trying to add a testcase name as a folder name. I am adding it in Teardown method to detect first whether to testcase passed or fail then accordingly it adds Folder in Pass or Fail Folder which already exist.
[Test]
public void TestCase12345()
{
string Name = methodBase.Name;
teardown(Name);
}
[TearDown]
public void teardown(string testcase)
{
if (TestContext.CurrentContext.Result.Status == TestStatus.Passed)
{
string sourcepath = #"sourcepath";
string timestamp = DateTime.Now.ToString("yy-MM-dd hh-mm");
string destpath = (#"destinationlocation" + "Test Case - " + testcase + " " + timestamp);
...
}
Error:
Invalid signature for SetUp or TearDown method: teardown
What am I missing over here?
You can't pass parameters to [TearDown] method, NUnit doesn't support it. For example, to pass parameters to [Test] you do something like this
[Test]
[TestCase("abc", 123)]
public void TestCase12345(string str, int number)
{
}
But as I said, NUnit doesn't support it in [TearDown].
As a side note, the check if the test succeeded should be in the test method (I find Assert very useful for that purpose). TearDown should be used only for the "cleaning", i.e. dispose of the WebDriver and any other things you created for the test and doesn't close automatically when the code is finished.
Edit
"Then what is the solution. how can add function name which I am calling it to create folder?"
You can implement an EventListener interface.
EventListeners are able to respond to events that occur in the course of a test run, usually by recording information of some kind.
For example
public class TestEventListaener : EventListener
{
// The test collection started/finished to run.
void RunStarted(string name, int testCount);
void RunFinished(TestResult result );
void RunFinished(Exception exception );
void TestStarted(TestName testName)
{
// create folder with the test name
}
void TestFinished(TestResult result)
{
// if test succeeded insert data to the folder otherwise delete it
}
// more `EventListener` methods
}
In addition to KjetilNodin's answer I would try removing the test case parameter from your tear down function since it is most likely expecting a function without parameters to be used for TearDown.
If you need this functionality I'd remove the TearDown attribute from the function and just call it at the end of your test case as in your example.
Two separate issues here:
1= As others have said, NUnit doesn't allow a teardown method to take an argument.
2 = If you call your method from the test, then it isn't functioning as a TearDown method but as part of the test code. The test has not yet finished, so it has no final result. What's more, if you should have a failed assert, you'll never reach the call.
You should remove the argument and the call. Use TestContext to get the test name as suggested in one of the comments.
I am writing an HTTP wrapper class object in C# and I would like to give the main method the ability to receive a function as a parameter and then execute it on the source HTML returned by the POST/GET.
For example I may want to pass a function that checks the headers for a cookie and only returns true if it's found OR pass a regular expression function that checks the source for a piece of content.
I know in PHP or JS I could easily just pass functions as parameters but I am not sure on how to go about it without creating delegates that match the functions I want to use.
I would like the code to be as "generic" as possible so that it could receive any function e.g Pseudocode would be like
public bool MakeHTTPRequest(string url, object possiblefunction)
{
make HTTP request
if status == 200
{
string response = getresponse
if(object is function){
call object
}
}
}
So the function may OR may NOT be passed in, or I may set a global property with it. Then I need to check IF a function exists and execute it if it does.
The function could be ANYTHING and I want to future proof the code so it can handle any kind of function in the future that maybe passed to it.
Any help would be much appreciated.
Thanks
Use either Func or Action (or Predicate as mentioned by DavidN) to specify the contract of delegates passed as a parameter into your MakeHTTPRequest method.
public bool MakeHTTPRequest(string url, Action possiblefunction)
{
make HTTP request
if status == 200
{
string response = getresponse
if(possiblefunction != null){
possiblefunction();
}
}
}
If your "function" returns a value/result then use Func instead..(where T is the expected return type)...e.g. Func<int>.
If your "function" expects parameters then specify the expected parameter types. So here are some examples:
Func<string,float,int> - a delegate which expects string and float parameters and returns an int result
Action - a delegate that takes no parameters, and doesn't return a value
Action<string,float> - a delegate that doesn't return a value (void), and expects a string and float as parameters.
http://www.blackwasp.co.uk/FuncAction.aspx
Func vs. Action vs. Predicate
If you're trying to pass back the "response" to the possiblefunction then do something like this.
public bool MakeHTTPRequest(string url, Action<string> possiblefunction)
{
make HTTP request
if status == 200
{
string response = getresponse
if(possiblefunction != null){
possiblefunction(response);
}
}
}
Based on the examples you've given, it seems that what you really want is to pass in a set of validators to determine if the HTTP response meets certain criteria. This seems to be further corroborated by the fact that your method is returning bool.
A Predicate<T>, or actually a set of Predicates, should encapsulate criteria rules that you pass in to determine whether the request is valid or not.
The signature for a Predicate<T> is bool Predicate<T>(T t) - meaning that it takes in some type and produces a bool
Using an array of predicates, and making sure they all pass, seems to be a pretty future-proof way for what you want to do
public bool MakeHTTPRequest(string url, params Predicate<WebResponse>[] validators)
{
// make HTTP requrest
var request = HttpWebRequest.Create(url);
var response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK){
foreach(var validator in validators)
if (!validator(response))
return false;
}
return true;
}
The trick is that the params keyword allows you to call the method passing in [0..any number] of values for the params, so all of the following invocations would work:
MakeHTTPRequest("http://stackoverflow.com");
MakeHTTPRequest("http://stackoverflow.com", r => r.Headers.AllKeys.Contains("CookieHeader"));
MakeHTTPRequest("http://stackoverflow.com", r => r.Headers.AllKeys.Contains("CookieHeader"), r => r.ContentLength < 10000);
Actually I need to know how this line is getting executed.
Example:
Browser("InternetExplorer").Page("Stackoverflow").WebElement("textbox").set "user"
The above lines executes like setting browser to Internet Explorer and finding page "stackoverflow" in it and then finding webelement "textbox" in it and then sets it values to "user". in this way the operation is done.
I want to know how this sequence call are be done. I don't want how browser is set to Internet Explorer and so on.
I need to execute a simple statement like
Fun("add").values("2,3").compute
I need the above line to execute by calling "add" function then values "2,3" are passed as parameter then "compute" add it and the final result should "5" be return.
How to do this? Whether we have to use different class for "Fun" and "values" or we need to implement them as "functions" of same class.
How to process sequence call ?
It is enough to return a reference to an existing object to achieve this effect:
class Operator
{
public:
Operator(const string& opAsStr)
{
...
}
Operator& Values(const string& operands)
{
....
return *this;
}
int Compute() // Compute must be a function, no properties in C++
{
...
}
};
// Usable like this
Operator("Add").Values("2,3").Compute()
By defining more function returning *this you can chain many calls. Note that you could return a value (i.e. Operator instead of a reference, or a const reference depending on your use cases).
You can also return a reference (or value) to an object of another class:
class A
{
public:
void DoSomething()
{
....
}
};
class B
{
public:
A MakeA()
{
return A();
}
};
B().MakeA().DoSomething();
I have a method, which returns void. It sets some values in an array, depending on an if/else statement.
However, if the code enters the else statement, this operation cannot be performed. What could I return to the calling method (a method in the code-behind of a winforms form), to indicate this operation did not suceed?
Thanks
You could change the void to int, bool or a result enumeration of some sort. The caller can then retrieve this value and check if the call was successful. For example, true is returned if the operation succeeded and false is returned if it didn't. If the method has to remain a void, you could use an out parameter which the caller then reads to check whether or not the call was successful. Alternatively, you could throw an exception and have the caller handle it.
you can use as OUT parameter, Out parameter must be assigned within the method, before it return the value or else compiler will raise the error.
void SomeFunction (someparameter of yor req, out bool result)
{
if(success) // if everty things go well, you assign out variable
{
result=true;
}
else
{
result=false;
}
}
Out Parameter Documentation
Have your method return a bool indicating success/failure.