How to test DAL implemented using linq2sql and Repository pattern? - unit-testing

Here is a part of my DAL.
DataContext interface:
public interface IDataContextFactory
{
System.Data.Linq.DataContext Context { get; }
void SaveAll();
}
Here is my data context class which contains generated classes:
partial class InternetRailwayTicketSalesDataContext: DataContext, IDataContextFactory
{
public System.Data.Linq.DataContext Context
{
get { return this; }
}
public void SaveAll()
{
this.SubmitChanges();
}
}
Here is my Repository interface:
public interface IRepository<T> where T : class
{
/// <summary>
/// Return all instances of type T.
/// </summary>
/// <returns></returns>
IEnumerable<T> GetAll();
}
Here is my Repository interface implementation:
public class Repository<T> : IRepository<T> where T : class
{
protected IDataContextFactory _dataContextFactory;
/// <summary>
/// Return all instances of type T.
/// </summary>
/// <returns></returns>
public IEnumerable<T> GetAll()
{
return GetTable;
}
private System.Data.Linq.Table<T> GetTable
{
get { return _dataContextFactory.Context.GetTable<T>(); }
}
}
Here is an interface for concrete repository class:
interface IPasswayRepository
{
bool IsPasswayExists(int id);
}
And finally here is a concrete repository class implementation:
class PasswayRepository:Repository<Passway>, IPasswayRepository
{
public PasswayRepository(IDataContextFactory context)
: base(context)
{
}
public bool IsPasswayExists(int id)
{
if (GetAll().Where(pass => pass.Id == id && pass.IsDeleted == false).Count() > 0)
return true;
else
return false;
}
}
Can you give me an example of how to test IsPasswayExists method? (you can use any mock framework if you want to).

Related

Akka Rest Server Jackson ObjectReader and ObjectWriter Initialization

I am using jackson ObjectReader and ObjectWriter object for serialization and deserialization in Akka Rest Server.
I am getting byteString in the request and deserialize it to object. Below is the scala code for it.
val a = objectReader.readValue[java.util.List[Base[Long]]](request.toArray)
Base class is an abstract class and I can have multiple implementation of it
#JsonTypeInfo(use = JsonTypeInfo.Id.NAME,
property = "impl")
#JsonSubTypes({
#JsonSubTypes.Type(value = A.class, name = "A")
})
public abstract class Base<T> implements Serializable {
private String impl;
private ResponseStatus status;
public String getImpl() {
return impl;
}
public void setImpl(String impl) {
this.impl = impl;
}
public void setStatus(ResponseStatus status) {
this.status = status;
}
public ResponseStatus getStatus() {
return status;
}
public static class ResponseStatus implements Serializable {
private ReturnCode code;
private String msg;
public void setCode(ReturnCode code) {
this.code = code;
}
public void setMsg(String msg) {
this.msg = msg;
}
public ReturnCode getCode() {
return code;
}
public String getMsg() {
return msg;
}
}
}
How ever I have observed that first call for readValue and writeValueAsBytes takes long.
I tried initializing it. But still it is not improving in Akka Execution Context. Anyone know the solution of it? Please help.

Mocking a singleton c# class in nunit

I have a class, something like this:-
namespace CalendarIntegration.Google
{
public sealed class GoogleSyncEventProcessor : ICalendarSyncEventProcessor
{
public void ProcessEventRequest(object events, int soUserId, string calendarId, bool addLogs = false)
{
if (GoogleWatchManager.Instance.IsGoogleTwoWaySynLive)
{
GoogleWatchManager is further a sealed class.
namespace CalendarIntegration.Google
{
public sealed class GoogleWatchManager
{
readonly bool isGoogleTwoWaySyncLive = true;
public GoogleWatchManager()
{
isGoogleTwoWaySyncLive = false;
}
virtual public bool IsGoogleTwoWaySynLive
{
get { return isGoogleTwoWaySyncLive; }
}
I want fake/mock GoogleWatchManager class and make the value of GoogleWatchManager.Instance.IsGoogleTwoWaySynLive in the nunit test cases, by default it is true in GoogleWatchManager class.
I tried the below but it doesn't work-
using EFBL;
using NUnit.Framework;
using EFBL.CalendarIntegration.CalendarSync;
using EFBL.CalendarIntegration.Google;
using Moq;
namespace EFBL.CalendarIntegration.Google
{
[TestFixture]
public class GoogleSyncEventProcessorSpec
{
public GoogleSyncEventProcessor google;
public GoogleWatchManager googleManager;
public void SetUp()
{
}
[Test]
public void ProcessEventRequest_NoEvents_ExceptionThrown()
{
var mock = new Mock<GoogleWatchManager>();
mock.SetupGet(foo => foo.IsGoogleTwoWaySynLive).Returns(true);
// watch.Setup(i => i.IsGoogleTwoWaySynLive).Returns(false);
// var mock = new Mock<GoogleWatchManager>().Object;
GoogleSyncEventProcessor obj = GoogleSyncEventProcessor.Instance;
obj.ProcessEventRequest(null, -1, "");
// isGoogleTwoWaySyncLive
}
}
}
Any help is highly appreciated, thanks in advance.
Here is the solution:-
using System;
using EFBL;
using NUnit.Framework;
using TypeMock.ArrangeActAssert;
using System.Diagnostics;
namespace EFBL.CalendarIntegration.Google
{
[TestFixture]
public class GoogleSyncEventProcessorSpec
{
public GoogleSyncEventProcessor googleSync;
public GoogleWatchManager googleManager;
[SetUp]
public void Init() {
googleManager = Isolate.Fake.Instance<GoogleWatchManager>();
googleSync = GoogleSyncEventProcessor.Instance;
}
[Test]
public void RequiresThatTwoWaySyncLiveBeFalse()
{
Isolate.NonPublic.Property.WhenGetCalled(googleManager, "IsGoogleTwoWaySynLive").WillReturn(false);
Assert.AreEqual(false, googleManager.IsGoogleTwoWaySynLive);
}

How to use Moq to Mock an internal class protected method?

I have classes below:
public class TestService
{
public void Upload()
{
var manager = new Manager();
var worker = manager.CreateWorker();
worker.DoWork();
}
}
public class Manager
{
public Worker CreateWork()
{
return new Worker();
}
}
public class Worker()
{
public void DoWork()
{
SetupEnvironment();
//some codes here...
}
protected virtual void SetupEnvironment()
{
//some codes here ...
}
}
I want to use Moq to create an unit test for Upload() method in TestService class, and SetupEnvironment() method of Worker should be mock up. I tried to the code below, but It doesnt' work:
[TestMethod]
public void Upload_Test()
{
var mockWorker = new Mock<Worker>();
mockWorker .Protected().Setup<string>("SetupEnvironment").Returns(() =>
{
//some dummy code here ...
});
var service = new TestService();
service.Upload();
Assert.IsTrue(true);
}
Anybody knows how to make the above unit test code work?
some things need to be changed. See the code of the class TestService and Worker below.
public class TestService
{
private readonly Manager _manager;
public TestService(Manager manager)
{
_manager = manager;
}
public void Upload()
{
var worker = _manager.CreateWorker();
worker.DoWork();
}
}
public class Manager
{
public virtual Worker CreateWorker()
{
return new Worker();
}
}
public class Worker
{
public void DoWork()
{
SetupEnvironment();
//some codes here...
}
protected virtual void SetupEnvironment()
{
//some codes here ...
}
}
Then the test could look like this. The method SetupEnvironment is void so the setup can't return any value and you need to mock the Manager as well and pass it to the TestService e.g. via constructor injection so you can inject your mock-object. HTH
[TestMethod]
public void Upload_Test()
{
bool setupEnvironmentWasCalled = false;
Mock<Worker> mockWorker = new Mock<Worker>();
mockWorker.Protected().Setup("SetupEnvironment")
.Callback(() =>
{
//some dummy code here ...
setupEnvironmentWasCalled = true;
});
Mock<Manager> mockManager = new Mock<Manager>();
mockManager.Setup(m => m.CreateWorker())
.Returns(mockWorker.Object);
var service = new TestService(mockManager.Object);
service.Upload();
Assert.IsTrue(setupEnvironmentWasCalled);
}

Failing in Code coverage Test with a simple class constructor

I have a class:
public class SourceServerProvider : ISourceServerProvider
{
private readonly ISourceServer _sourceServer;
public SourceServerProvider()
:this(new SourceServer())
{ }
public SourceServerProvider(ISourceServer sourceServer)
{
_sourceServer = sourceServer;
}
}
MS code coverage test complaints to this block:
public SourceServerProvider()
:this(new SourceServer())
{ }
I don't know how to write a unit test for above block. Please advise..
I just tested it with the followig code:
public class SourceServerProvider : ISourceServerProvider
{
private readonly ISourceServer _sourceServer;
public SourceServerProvider()
: this(new SourceServer())
{ }
public SourceServerProvider(ISourceServer sourceServer)
{
_sourceServer = sourceServer;
}
}
public interface ISourceServer
{
}
public class SourceServer : ISourceServer
{
}
public interface ISourceServerProvider
{
}
and wrote this test
public class Class1
{
[Test]
public void test()
{
var a = new SourceServerProvider();
}
}
Code Coverage says it is fully covered:
so please add the result you are getting or create asimple test that call the default ctor

MOQ returning null. [mock concrete class method]

[using Moq]
I am trying to mock a concrete class and mock a virtual method "Get()" of that class. When testing a method "GetItemsNotNull()" I always get returned null, instead of the return of the mocked function.
Here is the code
//SomeClasses.cs
namespace MoQExamples
{
public abstract class Entity
{
}
public class Abc : Entity
{
}
public interface IRepository<T> where T : Entity
{
IQueryable<T> Get();
}
public class Repository<T> : IRepository<T> where T : Entity
{
private readonly ISession _session;
public Repository()
{
_session = null;
}
public Repository(ISession session)
{
_session = session;
}
protected ISession CurrentSession
{
get { return _session; }
}
public virtual IQueryable<T> Get()
{
return CurrentSession.Query<T>();
}
}
public interface IAbcRepository
{
Abc GetItemsNotNull();
}
public class AbcRepository : Repository<Abc>, IAbcRepository
{
public Abc GetItemsNotNull()
{
return Get().FirstOrDefault(abc => abc !=null);
}
}
}
and here are the test class
namespace MoQExamples
{
[TestFixture]
public class SomeClassesTest
{
private readonly Mock<AbcRepository> _abcRepositoryMock = new Mock<AbcRepository>(MockBehavior.Strict) { CallBase = true };
[SetUp]
public void SetupTest()
{
_abcRepositoryMock.Setup(x => x.Get()).Returns(Get);
}
public IQueryable<Abc> Get()
{
return (new List<Abc>() { new Abc() }) as IQueryable<Abc>;
}
[Test]
public void TestGetItemsNotNull()
{
Assert.IsNotNull(_abcRepositoryMock.Object.GetItemsNotNull());
}
}
}
the assert alays fails..instead of returning the SomeClassesTest.Get()
thanks for advance guys!
I suspect this is the problem:
return (new List<Abc>() { new Abc() }) as IQueryable<Abc>;
List<T> doesn't implement IQueryable<T>, so this will always return null. Call AsQueryable to convert it instead:
return new List<Abc>().AsQueryable();
As an aside, this is a reason to prefer casts over as in most situations: if you'd just cast to IQueryable<Abc>, you'd have received an exception at the line which was really causing the problem. You should only use as when it's not a bug for the conversion to "fail". An as operator should almost always be followed by a nullity test.
(Note that this behaviour in itself has nothing to do with mocking or Moq. It's just the behaviour of the as operator...)