last day (15 days later) » 

7:34 PM
0
A: how to mock ITable with a concrete type

Patrick QuirkI see several issues with what you're trying to do. The posted code does not compile IDataContextWrapper.GetTable returns Table<T>, so you can't set it up to return a mocked ITable<T>. An ITable is not a Table, it's the other way around. This leads me to my next point: IDataContextWrapper.GetT...

 
Thanks Patrick for a very good explanation. However, I didn't understand one thing. That Table is not an Itable but its the other way around. As far as I remember,if a dog class implements an Animal interface then dog is an animal but animal is not dog.
This line mock.Setup(m => m.GetTable<Forum>()).Returns(tableMock.Object); gives the same invalid arguments error. Test Name: Can_Get_Forum_ById Result Message: Test method EpixForum.WebUI.Tests.UnitTest1.Can_Get_Forum_ById threw exception: System.NotSupportedException: Type to mock must be an interface or an abstract or non-sealed class. Result StackTrace: at Moq.Extensions.ThrowIfNotMockeable(Type typeToMock) at Moq.Mock1.CheckParameters() at Moq.Mock`1..ctor(MockBehavior behavior, Object[] args) at Moq.Mock`1..ctor() at EpixForum.WebUI.Tests.UnitTest1.Can_Get_Forum_ById()`
 
@user3527975 You're right, I screwed up which "is not" the other, fixed in an edit. The code compiles and runs for me. Did you change the return type of GetTable to ITable<T> (point #2), and tableMock is a mock of ITable<Forum>?
 
Yes. The IDataContextWrapper.GetTable returns an ITable<T> in my code. namespace EpixForum.Domain.Abstract { public interface IDataContextWrapper { ITable<T> GetTable<T>() where T : class ; } }
 
@user3527975 That error is saying you're trying to mock a sealed class, which Table is. What type is tableMock? It should be Mock<ITable<Forum>>, not Mock<Table<Forum>>. It's also being thrown in a Mock constructor, not on the line setting up the return value.
 
tableMock is Mock<ITable<Forum>>.
 
7:34 PM
@user3527975 Then you have code that I don't. Feel free to post more code, anything that's different or revised, as an edit to your question and I can help further.
So I'm missing something that you have, since everything works for me. Help me figure out what that is.
 
If I post most code in my question I fear it'll become very lengthy
Can i put the code here?
 
Start with the test method
Not sure, never tried
 
okay
public class UnitTest1
{
[TestMethod]
public void Can_Get_Forum_ById()
{
Forum dummyForum = new Forum { tblForumID = 1 };
IQueryable<Forum> forums = new List<Forum> { dummyForum }.AsQueryable();

Mock<ITable<Forum>> tableMock = new Mock<ITable<Forum>>();
tableMock.Setup(p => p.GetEnumerator()).Returns(forums.GetEnumerator());
tableMock.Setup(r => r.Provider).Returns(forums.Provider);
tableMock.Setup(r => r.ElementType).Returns(forums.ElementType);
tableMock.Setup(r => r.Expression).Returns(forums.Expression);
This is the test method
 
Ok, that compiles and passes for me
Show me the IDataContextWrapper definition
 
and this is the IDataContext Wrapper
namespace DiscussionForum.Domain.Abstract
{
public interface IDataContextWrapper
{
ITable<T> GetTable<T>() where T : class ;
}
}
 
7:38 PM
Also what I have, still no problems...
 
[global::System.Data.Linq.Mapping.TableAttribute(Name="dbo.tblForums")]
public partial class tblForum : INotifyPropertyChanging, INotifyPropertyChanged
{

private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(String.Empty);

private int _tblForumID;

private string _Name;
public tblForum()
{
this._tblThreads = new EntitySet<tblThread>(new Action<tblThread>(this.attach_tblThreads), new Action<tblThread>(this.detach_tblThreads));
OnCreated();
}

[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_tblForumID", AutoSync=AutoSync.OnInsert, DbType="Int NOT NULL IDENTITY", IsPrimaryKey=true, IsDbGenerated=true, UpdateCheck=UpdateCheck.Never)]
public int tblForumID
{
get
{
return this._tblForumID;
}
set
{
if ((this._tblForumID != value))
{
this.OntblForumIDChanging(value);
Forum is an autogenerated class
by Linq
 
None of that code is in your test that I can see, so it shouldn't matter
The exception that you get, is there a line number in it?
Or, can you debug the test to find the line throwing the exception?
 
I do not get a compile time exception
only when I run it gives this error
 
Run time exception, you do
Right
It should still report the line the exception occurs on
 
Line number is given as the starting line in the test method
I am sorry
not the method
namespace EpixForum.WebUI.Tests
{ -------------------------------> right here
[TestClass]
public class UnitTest1
{
[TestMethod]
public void Can_Get_Forum_ById()
{
Forum dummyForum = new Forum { tblForumID = 1 };
IQueryable<Forum> forums = new List<Forum> { dummyForum }.AsQueryable();
 
7:44 PM
That can't be right, there's no code there.
Are you sure you're running the newly written code?
I.e. you're not running tests using an old version of the code?
Put an Ignore attribute on the test and try to run it, it shouldn't run at all
 
okay
u're right
something's wrong
the test is still running
something's wrong
 
Well, that's good at least
You can try to clean and rebuild the solution
Or reload the assembly you're testing in whatever test runner you're using
 
okay
so theres a different error now
 
Great
 
Test Name: Can_Get_Forum_ById
Test FullName: DiscussionForum.WebUI.Tests.UnitTest1.Can_Get_Forum_ById
Test Source: c:\Users\Deepshikha\Documents\Visual Studio 2013\Projects\DiscussionForum\DiscussionForum.WebUI.Tests\UnitTest1.cs : line 26
Test Outcome: Failed
Test Duration: 0:00:00.8405661

Result Message:
Test method DiscussionForum.WebUI.Tests.UnitTest1.Can_Get_Forum_ById threw exception:
System.InvalidCastException: Unable to cast object of type 'Castle.Proxies.ITable`1Proxy' to type 'System.Data.Linq.Table`1[DiscussionForum.Domain.Database.tblForum]'.
I think i know where the error is coming from
Its this line ForumRepository repos = new ForumRepository(mock.Object);
 
7:56 PM
Sounds right, the ctor probably takes a Table, not an ITable?
 
The implementation of IDataContextWrapper also return an ITable
public ITable<TableName> GetTable<TableName>() where TableName : class
{
return (ITable<TableName>)db.GetTable(typeof(TableName));
}
but I have casted this ITable to Table in ForumRespository
public class ForumRepository : IForumRepository
{
protected Table<Forum> DataTable;
//DiscussionForumDataContext dataContext;
IDataContextWrapper DataContext;

public ForumRepository(IDataContextWrapper DataContext)
{
DataTable = (Table<Forum>)DataContext.GetTable<Forum>();
}
would it be alright if I use an Itable here too
 
Ah ok. That should be an ITable as well
 
is it alright to use an interface everywhere instead of concrete class?
 
Yes, in fact it's generally preferred. This is what I meant by "program to interfaces, rather than classes"
It decouples your code from the implementation (i.e. concrete classes), so you could swap them out for a different implementation
Like here, ITable<T> can point to either a Table<T> or a Mock<ITable<T>>
 
the purpose of ITable/Table in my code is only to fetch forums
by their id
also to deactivate them
when would an actual Table come into picture?
by actual I meant concrete
 
8:03 PM
I don't know enough about your system to say for sure
Whatever is creating the ForumRepository must get tables from somewhere
 
its the datacontext that is getting tables from database
 
Then thats where the concrete tables come from. But you'll probably never refer to them as the concrete type Table
Instead you'll likely always call them ITable to avoid problems like these
Were you able to get the test to pass?
 
there are some build errors else where in the code
so it doesn't run with the current changes
 
i guess they should run now
thanks Patrick
 
8:09 PM
Sure, happy to help
 
got to know quite a bit about testing and mocking
 
Good, there's always more to learn, too
 

last day (15 days later) »