public bool A (UserRequest foo)
{
ClientRequest boo = B(foo); //Mapping local model to client model
C(boo);
return result;
}
I want to write an unit test for method A to test method B but I don't want my unit test to call method C. Method C is a private method but it makes calls to a third party client. I am unable to setup method C in my Unit Test since the type "ClientRequest" doesn't have a reference in the test case assembly. How can this be implemented without adding a reference of the client dll to my test assembly as well. How to skip calling method C ?
C is a private method
Things are private for a reason. They are implementation details to which consuming code shouldn't be coupled. And unit tests are consuming code.
it makes calls to a third party client
Therein lies the problem with your unit tests. Don't try to break apart the class being tested, digging into its internals and ultimately modifying what it's doing and as a result invalidating the tests in the first place.
Instead, isolate and mock the dependency. Somewhere in C() this class has an external dependency. Instead of obscuring that dependency deep within the class, wrap it in an interface/implementation and provide that implementation to the class. (This is called Dependency Injection. There are frameworks which provide rich functionality around the concept, but the concept itself can be achieved manually for simple cases as well.)
So when application code uses this class, instances are provided with an implementation of the dependency which calls the external service. And when unit tests use this class, instances are provided with a mock implementation that pretends to call the external service.
Then your tests can include mocking the results of that service as well, triggering controlled failure responses to test how the class handles them.
Related
A method in the service which I'm unit testing is calling a static method that is present in another service.
I'm new to unit testing and have no idea how to mock these kinda dependencies. Please suggest!
There is already a thread here about this topic.
In fact it is not possible to create a service facade (Mock) for static methods.
My suggestion here is to refactor your code in that way that you make your class non static and create an interface for it. Than you can inject your dependency class in the normal system via IOC and in the unit test you can create a mock with frameworks like Moq or Rhinomocks.
Suppose you have a vendor application (and associated closed vendor API) which makes calls on C# 'plugin' code written by the customer. Plugins implement abstract classes defined by the vendor. For example
public class MyPlugin : AbstractVendorPlugin
{
public override VendorClass PluginMain(VendorClass vc, VendorFactory vf)
{
vc.AddCalculation("x => x*x");
ExecutionContext ec = vf.CreateExecutionContext();
vc.Execute(ec);
return vc;
}
}
The handles for the classes/factories passed into the plugin area are created by the vendor application, and cannot be created outside of that application (and let us assume that our build server cannot spontaneously create an application instance).
I am unsure of how to proceed with making the plugin code unit testable. The only option I can come up with is to wrap the objects in interfaces and then limit tests to test cases which count invocations and validate inputs on those invocations (outputs cannot be verified if they are vendor objects). This seems to not provide much value.
Is there another option here I am not seeing? Does unit testing a plugin paradigm like this even make sense?
The intention of unit tests is to verify the behavior of the object under test. Unit test should be fast and don't depend on third parties.
The intention of integration test is to verify the end to end behaviour.
So your approach for unit tests is right. First wrap vendors object, substitute real implementation with your mocked object, assert that your code calls vendor's object in correct way with correct parameters. You should not execute full flow as it not unit tests responsibility.
I have tests written in XUnit using InlineData and MemberData attributes. I would like to run tests via code elsewhere in my project and have the attributes automatically fill in test data like they normally do when ran through the VS test runner.
If it weren't for the attributes I would just call the methods directly like any other normal method. The asserts are still checked and it functions fine. But if I call a method directly that has the attributes, the attributes are ignored and I must provide all the test data manually through code. Is there some sort of test runner class in XUnit that I can reuse to accomplish this? I've been trying to dig through their API to no avail.
Why I want to do this will take some explanation, but bear with me. I'm writing tests against specific interfaces rather than their concrete implementations (think standard collection interfaces for example). There's plenty there to test and I don't want to copy paste them for each concrete implementer (could be dozens). I write the tests once and then pass each concrete implementation of the interface as the first argument to the test, a subject to test on.
But this leaves a problem. XUnit sees the test and wants to run it, but it can't because there are no concrete implementations available at this layer, there's only the interface. So I want to write tests at the higher layer that just new up the concrete implementations, and then invoke the interface tests passing in the new subjects. I can easily do this for tests that only accept 1 argument, the subject, but for tests where I'm using InlineData or MemberData too I would like to reuse those test cases already provided and just add the subject as the first argument.
Available for reference is the GitHub issue How to programmatically run XUnit tests from the xUnit.net project.
The class AssemblyRunner is now part of Xunit.Runner.Utility.
From the linked issue, xUnit.net contributor Brad Wilson provided a sample runner in the samples.xunit project on GitHub. This program demonstrates the techniques described in the issue. Namely, the portion responsible for running the tests after they have been discovered is as follows:
using (var runner = AssemblyRunner.WithAppDomain(testAssembly))
{
runner.OnDiscoveryComplete = OnDiscoveryComplete;
runner.OnExecutionComplete = OnExecutionComplete;
runner.OnTestFailed = OnTestFailed;
runner.OnTestSkipped = OnTestSkipped;
Console.WriteLine("Discovering...");
runner.Start(typeName);
finished.WaitOne(); // A ManualResetEvent
finished.Dispose();
return result;
}
For a deeper dive, he describes a method using XunitFrontController and TestDiscoveryVisitor to find and run tests. This is what AssemblyRunner does for its implementation.
Nevermind, I figured it out. Taking a closer look at XUnit's attribute hierarchy I found that the DataAttributes (InlineData, MemberData, etc) have a GetData method you can call to retrieve the set of data they represent. With a little reflection I can easily find all the tests in my test class and call the test methods, invoking the data attribute's get data method if there are any present, and perform the tests via my own code that way. The GetData part would have been much harder if I had to role my own version of it. Thank you XUnit authors for not forcing me to do that.
I'm relatively new to unit testing, and very new to C#, but I've been trying to test code that uses static classes with static methods, and it seems like I have to write huge amounts of boilerplate code in order to test, and that code would then also probably need to be tested.
For example: I'm using the System.Web.Security.Membership class, with a method ValidateUser on it. It seems like I need to create an interface IMembership containing the method ValidateUser, then create a class MembershipWrapper that implements IMembership, implementing the method ValidateUser and passing the arguments on to the actual Membership class. Then I need to have properties on my class that uses the Membership to reference the wrapper so that I can inject the dependency for a mock object during testing.
So to test 1 line of code that uses Membership, I've had to create an interface, and a class, and add a property and constructor code to my class. This seems wrong, so I must be getting something wrong. How should I be going about this testing? I've had a brief look at some frameworks/libraries that do dependency injection, but they still appear to require lots of boilerplate, or a very deep understanding of what's going on under the hood.
I don't see anything wrong in making your system loosely coupled. I believe you don't complain on creating constructor parameters and passing abstract dependencies to your classes. But instantiating dependencies in place looks so much easier, does it?
Also, as I pointed in comments, you can reuse wrappers later. So, that is not such useless work, as it seems from first glance.
You are on the right way, and think you are not testing single line of code, in this case you are writing important test to ensure that your code interacts with membership provider in the right way, this is not simple unit test rather "mock-based" integration test. I think it worth creating all these mocks and have covered by tests this part of application.
And yes, it seems overkill but no other way - either you use some helpers/libraries either wrap third-party static dependencies yourself.
I you're not happy taking the approach of constructor injection, you could look at using Ambient Context
You basically set up a default which will call System.Web.Security.Membership.ValidateUser
You then call the exposed method on the context in your code and you can now mock it for your tests
This allows you to write less setup code, but it also hides the fact that you have a dependency, which might be a problem in the future (depending on how you're reusing code)
If you're using VS2012, you can always use Shims in Microsoft Fakes for static calls (or .Net library calls too).
http://msdn.microsoft.com/en-us/library/hh549175(v=vs.110).aspx
http://msdn.microsoft.com/en-us/library/hh549176.aspx
How can I test the following method?
It is a method on a concrete class implementation of an interface.
I have wrapped the Process class with an interface that only exposes the methods and properties I need. The ProcessWrapper class is the concrete implementation of this interface.
public void Initiate(IEnumerable<Cow> cows)
{
foreach (Cow c in cows)
{
c.Process = new ProcessWrapper(c);
c.Process.Start();
count++;
}
}
There are two ways to get around this. The first is to use dependency injection. You could inject a factory and have Initiate call the create method to get the kind of ProcessWrapper you need for your test.
The other solution is to use a mocking framework such as TypeMock, that will let you work around this. TypeMock basically allows you to mock anything, so you could use it to provide a mock object instead of the actual ProcessWrapper instances.
I'm not familiar with C# (I prefer mine without the hash), but you need some sort of interface to the process (IPC or whatever is the most convenient method) so you can send it test requests and get results back. At the simplest level, you would just send a message to the process and receive the result. Or you could have more granularity and send more specific commands from your test harness. It depends on how you have set up your unit testing environment, more precisely how you send the test commands, how you receive them and how you report the results.
I would personally have a test object inside the process that simply receives, runs & reports the unit test results and have the test code inside that object.
What does your process do? Is there any way you could check that it is doing what it's supposed to do? For example, it might write to a file or a database table. Or it might expose an API (IPC, web-service, etc.) that you could try calling with test data.
From a TDD perspective, it might make make sense to plug in a "mock/test process" that performs some action that you can easily check. (This may require code changes to allow your test code to inject something.) This way, you're only testing your invocation code, and not-necessarily testing an actual business process. You could then have different unit tests to test your business process.