Reputation: 779
I want to test a class that uses Linq to SQL. I have faked the datacontext with TypeMock Isolator, but the datacontext also has a function that I don't know how to fake. This function is used in Linq to Sql-queries.
The function passes two arguments (int? a, string b), and returns an integer; DC.MyMethod(int? a, string b)
How to I fake this?
//Fake datacontext
var fakeDC = Isolate.Fake.Instance<MyDataContext>();
//Fake --> this doesn't work
Isolate.WhenCalled((int? a, string b) => fakeDC.MyFunction(a,b).... ?
Hope anyone can help
Upvotes: 1
Views: 716
Reputation: 449
Disclaimer, I work in Typemock.
To avoid exceptions you should fake all future instatnces of MyDataContext:
var fakeDC = Isolate.Fake.AllInstances<MyDataContext>();
And then set the behavior fo MyFunction():
int? id = 10;
string name = "David";
Isolate.WhenCalled(() => fakeDC.MyFunction(id, name)).WithExactArguments().WillReturn(..);
It makes sure that all instances of MyDataContext will be faked (created by new MyDataContext() in any part of your program), and MyFunction() behavior will be faked as well.
Since i don't know all the details, check the example below for more understanding:
internal class Foo
{
public Foo()
{
}
public int Bar()
{
var x = new MyDataContext();
return x.MyFunction(null, "5");
}
}
public class MyDataContext : DataContext
{
//
public int MyFunction(int? a, string b)
{
if(a == null)
{
throw new Exception();
}
return 0;
}
}
[TestMethod, Isolated]
public void TestMyDataContext()
{
//Arrange
var fakeDC = Isolate.Fake.AllInstances<MyDataContext>();
Isolate.WhenCalled(() => fakeDC.MyFunction(null, "5")).WithExactArguments().WillReturn(6);
//Act
var foo = new Foo();
var res = foo.Bar();
//Assert
Assert.AreEqual(6, res);
}
See all information in our docs.
Upvotes: 1
Reputation: 31548
Isolator by default ignores arguments passed to functions. To fake yours, you could simply use:
Isolate.WhenCalled(() => fakeDC.MyFunction(null, null)).WillReturn(...)
If you need to make sure it was called with specific arguments, add WithExactArguments()
, like this:
int? id = 10;
string name = "David";
Isolate.WhenCalled(() => fakeDC.MyFunction(id, name)).WithExactArguments().WillReturn(...);
Hope that helps.
Upvotes: 3