Telerik Forums
JustMock Forum
1 answer
134 views
Help me to complete the test methods for below code
I have one method OrderProducts in Shop class  which  place the order or request new stock when products are not there.
Can you help me mock the local call and external call.
There is method OrderProducts and against each line of the code I provided the comments what I want to mock in the Testmethods. 

Copy paste the below code in one .cs file of JustMockTest project
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;
using System.ServiceModel;
using System.ServiceModel.Channels;
  
 
namespace Business
{
    public class Shop
    {
        public Shop() { }
        public void OrderProducts()
        {
            LogInfo log = new LogInfo();//From the test method should be able to  skip  this constructor assume there is big amount of the dependent code in the constructor   
            CategoryType cat = new CategoryType();
            cat.Level = 2; //From the test method should be able to set cat.Level equal to 10
            var categories = CategoryHelper.GetCategories(cat); //want pass cat level 3 and return any three item
            this.CategoriesList = categories;
            bool retval = true; //From the test method should be able to set retval equal to false
            IProductService productProxy = WCFServicesInstance.GetWCFServiceInstance<IProductService>();
             
            List<Product> productlist = productProxy.ProductsByCategories(log, CategoriesList);
            
           if(productlist.Count>0)
           {
                
               int orderID=PlacetheOrder(productlist); //From the test method should be able to call another method like DoInstead
 
           }
           else 
           {
               RequestNewStock(productlist);//From the test method should be able to call another method like DoInstead
           }
 
             OnClose(); //From the test method should be able to ignore the call
        }
 
        private int PlacetheOrder(List<Product> productlist)
        {
            throw new NotImplementedException();
        }
 
        private void RequestNewStock(List<Product> productlist)
        {
            throw new NotImplementedException();
        }
 
        private void OnClose()
        {
             throw new NotImplementedException();
        }
        private  List<Category> categoriesList;
 
        public  List<Category> CategoriesList
        {
            get { return categoriesList;}
            set { categoriesList = value;}
        }
     
 
 
 
    }
 
    public class Product
    {
    }
 
    public class LogInfo
    {
    }
    public class Category
    {
       private string name;
 
    public string Name
    {
        get { return name;}
        set { name = value;}
    }
     
    }
    public class CategoryType
    {
        private int level;
 
        public int Level
        {
            get { return level; }
            set { level = value; }
        }
         
    }
 
    public class CategoryHelper
    {
       public static List<Category> GetCategories(CategoryType cat)
        {
            throw new NotImplementedException();//This making external call
        }
    }
 
    public interface IProductService : IDisposable
    {
      
     List<Product> ProductsByCategories(LogInfo log,List<Category> CategoriesList);
    }
    public class WCFServicesInstance
    {
 
        public WCFServicesInstance() { }
        public static T GetWCFServiceInstance<T>() where T : class, IDisposable
        {
            T retVal;
                       
            retVal = GetProxyInstance<T>().ProxyContract;
            return retVal;
        }
        public static WCFServiceProxy<T> GetProxyInstance<T>() where T : class
        {
             
            WCFServiceProxy<T> wcfProxy = null;
            #region There is external call that gives the instance
            //External dlll that gives instance of WCFServiceProxy<T>
            #endregion
            return wcfProxy;
        }
    }
    public class WCFServiceProxy<T> : ClientBase<T> where T : class
    {
        public WCFServiceProxy() {}
        public T ProxyContract { get; set; }
    }
}
 
Here are the tried test method.  You can paste it another .cs file

using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Business;
using Telerik.JustMock;
namespace JustMockTestProject
{
    [TestClass]
    public class ShopTest
    {
        [TestMethod]
        public void OrderProductsPlaceOrderTest()
        {
            #region Arrange
            var loginfo = Mock.Create<v>();
            CategoryType cat = new CategoryType();
            cat.Level = 3;
           //  Mock.Arrange(() => CategoryHelper.GetCategories(cat)).Returns(cat);
            #endregion
            #region Act
            Shop target = new Shop();
            target.OrderProducts();
            #endregion
            #region Assert
            //Assert that Order is place i.e PlacetheOrder is called(mock version)
 
            #endregion
        }
 
        [TestMethod]
        public void OrderProductsRequestNewStockTest()
        {
            #region Arrange
            #endregion
            #region Act
            Shop target = new Shop();
            target.OrderProducts();
            #endregion
            #region Assert
            //Assert that Product are Requested for the new stock i.e RequestNewStock is called (mock version)
            #endregion
        }
    }
}


Kaloyan
Telerik team
 answered on 15 Feb 2013
4 answers
236 views
If I'm have a class as a parameter to a mocked method, what does JustMock use to determine whether the parameters match or not?

e.g.

public class Bi
{
    protected bool Equals(Bi other)
    {
        return I == other.I;
    }
 
    public override int GetHashCode()
    {
        return I;
    }
 
    public override bool Equals(object obj)
    {
        return base.Equals(obj);
    }
    public int I { get; set; }
}
 
public interface IR
{
    bool Get(Bi bi);
}
 
public class G
{
    private readonly IR _r;
 
    public G(IR r)
    {
        _r = r;
    }
 
    public bool M()
    {
        var bi = new Bi {I = 1};
        return _r.Get(bi);
    }
}
 
[TestFixture]
public class Test
{
    [Test]
    public void Test1()
    {
        var bi = new Bi {I = 1};
        var r = Mock.Create<IR>();
 
        Mock.Arrange(() => r.Get(bi)).Returns(true);
        var g = new G(r);
        var b = g.M();
        Assert.That(b, Is.True);
    }
 
}
No matter what I do, I can't seem to get  the BI parameter to match correctly.
I've tried Equals and a bunch of the interfaces for testing equality and none seem to get called.
Do I need to use the Arg.Matches or should this work and I'm just missing something?
Mihail
Telerik team
 answered on 14 Feb 2013
5 answers
235 views
I installed the JustMock Q3 2012 SP2 trial version.
I am getting the above error. I also attached the stack trace.
Do let me any step i missed while running the sample test cases.

Thanks
Mohd Moyeen
Kaloyan
Telerik team
 answered on 12 Feb 2013
5 answers
320 views
I have the following Arrange code
var oRegMgr = Mock.Create<IRegionManager>();
var oCmdRegion = Mock.Create<IRegion>();
var oCmdView = Mock.Create<CommandingView>(Constructor.Mocked);
 
Mock.Arrange(() => oRegMgr.Regions[RegionNames.CommandingRegion]).Returns(oCmdRegion);
Mock.Arrange(() => oCmdRegion.ActiveViews.FirstOrDefault()).Returns(oCmdView);

This calls a function that does this
IRegion commandingRegion = oRegionManager.Regions[RegionNames.CommandingRegion];
CommandingView oCmdView = (CommandingView)commandingRegion.ActiveViews.FirstOrDefault();

(the region manager is returned via a previous call that supplies the mocked region manager, bu that is not germane here, so I have concentrated on the problem area. The access to the region manager sequence is used in several other unit tests, and works fine. When I step thru this in debug, the ProxyRegionManager is in fact the one being used).
I get the mocked region back from oRegionManager just fine. However, when the call to get FirstOrDefault happens, it returns null, NOT the mocked CommandingView.
Am I missing something in the Arrange for invoking FirstOrDefault?

Thanks

Kaloyan
Telerik team
 answered on 12 Feb 2013
7 answers
1,000 views
What is the just mock equivalent of setting the value of a private member variable?

public class foo
{
private IEventAggregator _ea;
...
}

I just want to do something like this:

foo mockedFoo = Mock.Create<foo>();
IEventAggregator fakeEA = Mock.Create<IEventAggregator>();
Mock.NonPublic.Arrange(foo, "_ea", fakeEA);

But this is not working for me and gives me an error:
System.ArgumentException: Could not resolve the target method; make sure that you have provided arguments correctly.
Kaloyan
Telerik team
 answered on 05 Feb 2013
1 answer
109 views
I posted a support ticket for this, but thought I'd ask in the forum as well. As show below, I attempt to JustMock a Prism view. When this unit test runs, and this line is encountered, I get an exception complaining that cannot locate the corresponding XAML for the view. The stack shows us  in the constructor of the CommandingView class, calling InitializeComponent, which does not sound like mocking. The text of the excpetion is:
{"The component 'CommandingViewProxy\\+6068b00980684baaaf2f95f50b66a803' does not have a resource identified by the URI '/Infrastructure;component/views/commandingview.xaml'."}

It seems I should possibly be doing something additional to JustMock a Prism view. Or some other setup is needed.
Anyone got any suggestions?
var oCmdView = Mock.Create<CommandingView>();
Kaloyan
Telerik team
 answered on 04 Feb 2013
11 answers
241 views

Hi, I'm trying to unit test a common interface used in a generic Repository, something like T GetWhere(Func<T, Boolean> where)...
When I set this expectation in a test

Mock.Arrange(() => bookRepo.GetWhere(book => book.Id == 1))
                 .Returns(expectedBook)
                 .MustBeCalled();

JustMock throws this exception:  "Telerik.JustMock.MockAssertionException: Setup contains calls that are marked as "MustBeCalled" but actually never called"
It seems the GetWhere() method was never call, to return the expected object.
Below is a simple example that illustrate the case.  
How should I rewrite the second test below so that I can mock and test these type of interfaces? 
Thanks in advance. 

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Telerik.JustMock; //Free version 2011.1.331.1
using Model.Infrastructure;
using Model;
  
namespace Model.Infrastructure
{
    public interface IRepository<T> where T : class
    {
        T GetById(int Id);
        T GetWhere(Func<T, Boolean> where);
    }
}
  
namespace Model
{
    public class Book
    {
        public int Id { get; set; }
        public string BookTitle { get; set; }
        public string OnLoanTo { get; set; }
        public Book(){}
    }
  
    public class BookService
    {
        private IRepository<Book> _bookRepository;
        public BookService(IRepository<Book> bookRepository)
        {
            this._bookRepository = bookRepository;
        }
  
        public Book GetSingleBook1(int bookId)
        {
            return _bookRepository.GetById(bookId);;
        }
  
        public Book GetSingleBook2(int bookId)
        {
            Book b = _bookRepository.GetWhere(x => x.Id == bookId);
            return b;
        }
    }
}
  
namespace Model.Tests
{
    [TestClass]
    public class AssortedTests
    {
        private Book expectedBook;
        private IRepository<Book> bookRepo;
        private BookService bookService;
  
        [TestInitialize]
        public void Setup()
        {
            expectedBook = new Book()
            { Id = 1,
              BookTitle =
"Adventures",
              OnLoanTo =
"John Smith"
            };
            bookRepo = Mock.Create<IRepository<Book>>();
            bookService = new BookService(bookRepo);
        }
  
        [TestMethod]
        public void Book_CanRetrieveBookFromRepository()
        {
            Mock.Arrange(() => bookRepo.GetById(1))
                             .Returns(expectedBook)
                             .MustBeCalled();
            //Act
            Book actualBook = bookService.GetSingleBook1(1); 
  
            Mock.Assert(bookRepo); //Pass...
            Assert.IsTrue(actualBook.BookTitle == "Adventures");
        }
  
        [TestMethod]
        public void Book_CanRetrieverFromRepositoryUsingLambdaExpressions()
        {
            Mock.Arrange(() => bookRepo.GetWhere(book => book.Id == 1))
                             .Returns(expectedBook)
                             .MustBeCalled();
            //Act
            Book actualBook = bookService.GetSingleBook2(1);
  
            Mock.Assert(bookRepo); //Throws the error...
            Assert.IsTrue(actualBook.BookTitle == "Adventures");
        }
    }
}
Ricky
Telerik team
 answered on 30 Jan 2013
1 answer
218 views
Is it possible to mock the static FormsAuthentication?  I would like to check that the SignIn and SignOut methods are called in an MVC LoginController.

I have a mocked LoginController, lc, and the following code:

Mock.SetupStatic(typeof(FormsAuthentication));
            Mock.Arrange(() => FormsAuthentication.SignOut()).OccursOnce();
 
            var result = lc.Logoff();
 
            Mock.Assert(() => FormsAuthentication.SignOut());

If I run this under debug it passes but if I just run it I get:
Test Name:  LogoffShouldCallFormsAuthenticationSignOut
Test FullName:  OfDisplays.WebTests.SecurityTests.LogoffShouldCallFormsAuthenticationSignOut
Test Source:    c:\SoftDev\Projects\OFDisplays\OfDisplays.Web\OfDisplays.WebTests\SecurityTests.cs : line 83
Test Outcome:   Failed
Test Duration:  0:00:01.9634171
 
Result Message:
Test method OfDisplays.WebTests.SecurityTests.LogoffShouldCallFormsAuthenticationSignOut threw exception:
System.IO.FileNotFoundException: Could not load file or assembly 'Telerik.CodeWeaver.Api, Version=1.0.0.0, Culture=neutral, PublicKeyToken=87210992829a189d' or one of its dependencies. The system cannot find the file specified.WRN: Assembly binding logging is turned OFF.
To enable assembly bind failure logging, set the registry value [HKLM\Software\Microsoft\Fusion!EnableLog] (DWORD) to 1.
Note: There is some performance penalty associated with assembly bind failure logging.
To turn this feature off, remove the registry value [HKLM\Software\Microsoft\Fusion!EnableLog].
Result StackTrace: 
at System.Web.Security.FormsAuthentication.SignOut()
   at OfDisplays.Web.Controllers.LoginController.Logoff() in c:\SoftDev\Projects\OFDisplays\OfDisplays.Web\OfDisplays.Web\Controllers\LoginController.cs:line 57
   at OfDisplays.WebTests.SecurityTests.LogoffShouldCallFormsAuthenticationSignOut() in c:\SoftDev\Projects\OFDisplays\OfDisplays.Web\OfDisplays.WebTests\SecurityTests.cs:line 90

Kaloyan
Telerik team
 answered on 30 Jan 2013
6 answers
674 views
Hi There, 

Can anyone give me a hand of how to mock internal new instance in my unit test? my method like below:

        public List<Driver> SearchByDriverName(string driverName, bool? status)
        {
            IDriverDAC driverDAC = new DriverDAC();
            List<Driver> drivers = new List<Driver>();
            drivers = driverDAC.SearchByDriverName(driverName, status);
            return drivers;
        }

here i want to test this method, the first thing i need to do is mock the DriverDAC (mock driverDAC.SearchByDriverName 
method), but the issue is the DriverDAC
is not injected into this class, it is created by new instance, so i can not mock & by pass the SearchByDriverName method,
can anybody give me a light of how to do it? understand it is better to use DI to inject the class,
but due to some special reason by user, we can not change the design structure now.

Thanks!

Suyi


Kaloyan
Telerik team
 answered on 28 Jan 2013
3 answers
100 views
Hi,

I want to mock the webservice proxy class autogenerated by VS 2012, and when I call Mock.Create<portailSOAPClient>(), I have an ArgumentNullException.

   à System.IO.BinaryReader..ctor(Stream input, Encoding encoding, Boolean leaveOpen)
   à System.IO.BinaryReader..ctor(Stream input)
   à Telerik.JustMock.AssemblyBuilderHelper.ReadStrongKeyNamePairFromManifest()
   à Telerik.JustMock.AssemblyBuilderHelper.GetModuleBuilder(Boolean strongNamedAssembly)
   à Telerik.JustMock.AssemblyBuilderHelper.DefineModule(Type targetType)
   à Telerik.JustMock.Weaver.WeaverAssemblyBuilder.BuildDynamicAssembly(MethodBase methodBase, ModuleBuilder& moduleBuilder)
   à Telerik.JustMock.Weaver.DynamicInjector.Inject(Type targetType, MethodBase methodBase, MethodBase containerMethodInfo)
   à Telerik.JustMock.Weaver.DynamicInjector.Inject(Type targetType, MethodBase methodBase, MethodBase injectingMethod, Boolean force)
   à Telerik.JustMock.Weaver.DynamicInjector.Inject(Type targetType, MethodBase methodBase)
   à Telerik.JustMock.MockManager.SetupMock(Behavior behavior, Boolean static)
   à Telerik.JustMock.MockManager.CreateInstance()
   à Telerik.JustMock.FluentMock.Create()
   à Telerik.JustMock.Mock.Create(Type target, Action`1 settings)
   à Telerik.JustMock.Mock.Create(Type targetType, Constructor constructor, Behavior behavior)
   à Telerik.JustMock.Mock.Create[T](Constructor constructor)  

The proxy class generated by VS2012 is :
public partial class portailSOAPClient : System.ServiceModel.ClientBase<FiduPortail.portailSOAP>, FiduPortail.portailSOAP {}
     
Do you know how to resolve this issue.

Regards,
Mihail
Telerik team
 answered on 28 Jan 2013
Narrow your results
Selected tags
Tags
+? more
Top users last month
Jay
Top achievements
Rank 3
Bronze
Iron
Iron
yw
Top achievements
Rank 2
Iron
Iron
Stefan
Top achievements
Rank 2
Iron
Iron
Iron
Kao Hung
Top achievements
Rank 1
Iron
Bohdan
Top achievements
Rank 2
Iron
Iron
Iron
Want to show your ninja superpower to fellow developers?
Top users last month
Jay
Top achievements
Rank 3
Bronze
Iron
Iron
yw
Top achievements
Rank 2
Iron
Iron
Stefan
Top achievements
Rank 2
Iron
Iron
Iron
Kao Hung
Top achievements
Rank 1
Iron
Bohdan
Top achievements
Rank 2
Iron
Iron
Iron
Want to show your ninja superpower to fellow developers?
Want to show your ninja superpower to fellow developers?