I am trying to write some unit tests for controller actions.  To do that, I am using XUnit and Moq.  The controllers have an ILoggerFactory injected in the constructor.  How does one Moq this up for testing?    I have tried mocking a Logger for the controller class, and then mocking up CreateLogger to return the mock Logger, but I keep getting various test runtime NullReferenceExceptions when the LogInformation() function is called.          //   Logger that yields only disappointment...                   var mockLogger = new Mock&lt;ILogger&lt;JwtController&gt;&gt;();         mockLogger.Setup(ml =&gt; ml.Log(It.IsAny&lt;LogLevel&gt;(), It.IsAny&lt;EventId&gt;(), It.IsAny&lt;object&gt;(), It.IsAny&lt;Exception&gt;(), It.IsAny&lt;Func&lt;object, Exception, string&gt;&gt;()));         var mockLoggerFactory = new Mock&lt;ILoggerFactory&gt;();         mockLoggerFactory.Setup(mlf =&gt; mlf.CreateLogger("JwtController")).Returns(mockLogger.Object);   I assume the problem is that LogInformation is being called, and this is an extension method, so how to moq that?
33300
I am writing a test that depends on the results of an extension method but I don't want a future failure of that extension method to ever break this test. Mocking that result seemed the obvious choice but Moq doesn't seem to offer a way to override a static method (a requirement for an extension method). There is a similar idea with Moq.Protected and Moq.Stub, but they don't seem to offer anything for this scenario. Am I missing something or should I be going about this a different way?  Here is a trivial example that fails with the usual "Invalid expectation on a non-overridable member". This is a bad example of needing to mock an extension method, but it should do.  public class SomeType {     int Id { get; set; } }  var ListMock = new Mock&lt;List&lt;SomeType&gt;&gt;(); ListMock.Expect(l =&gt; l.FirstOrDefault(st =&gt; st.Id == 5))         .Returns(new SomeType { Id = 5 });   As for any TypeMock junkies that might suggest I use Isolator instead: I appreciate the effort since it looks like TypeMock could do the job blindfolded and inebriated, but our budget isn't increasing any time soon.
30349
I'm working on a large c++ system that is has been in development for a few years now. As part of an effort to improve the quality of the existing code we engaged on a large long-term refactoring project.  Do you know a good tool that can help me write unit tests in C++? Maybe something similar to Junit or Nunit?  Can anyone give some good advice on the methodology of writing unit tests for modules that were written without unit testing in mind?
22560
I'm writing code to do Xml serialization. With below function.  public static string SerializeToXml(object obj) {     XmlSerializer serializer = new XmlSerializer(obj.GetType());     using (StringWriter writer = new StringWriter())     {         serializer.Serialize(writer, obj);         return writer.ToString();     } }   If the argument is a instance of class without parameterless constructor, it will throw a exception.     Unhandled Exception:   System.InvalidOperationException:   CSharpConsole.Foo cannot be serialized   because it does not have a   parameterless constructor.    at   System.Xml.Serialization.TypeDesc.CheckSupported()   at   System.Xml.Serialization.TypeScope.GetTypeDesc(Type   type, MemberInfo sourc e, Boolean   directReference, Boolean throwOnError)   at   System.Xml.Serialization.ModelScope.GetTypeModel(Type   type, Boolean direct Reference)    at   System.Xml.Serialization.XmlReflectionImporter.ImportTypeMapping(Type   type , XmlRootAttribute root, String   defaultNamespace)    at   System.Xml.Serialization.XmlSerializer..ctor(Type   type, String defaultName space)    at   System.Xml.Serialization.XmlSerializer..ctor(Type   type)   Why must there be a parameterless constructor in order to allow xml serialization to succeed?  EDIT: thanks for cfeduke's answer. The parameterless constructor can be private or internal.
103121
I am attempting to mock a call to an indexed property. I.e. I would like to moq the following:  object result = myDictionaryCollection["SomeKeyValue"];   and also the setter value  myDictionaryCollection["SomeKeyValue"] = myNewValue;   I am doing this because I need to mock the functionality of a class my app uses.   Does anyone know how to do this with MOQ? I've tried variations on the following:  Dictionary&lt;string, object&gt; MyContainer = new Dictionary&lt;string, object&gt;(); mock.ExpectGet&lt;object&gt;( p =&gt; p[It.IsAny&lt;string&gt;()]).Returns(MyContainer[(string s)]);   But that doesn't compile.  Is what I am trying to achieve possible with MOQ, does anyone have any examples of how I can do this?
10722
I am trying to run some unit tests in a C# Windows Forms application (Visual Studio 2005), and I get the following error:  System.IO.FileLoadException: Could not load file or assembly 'Utility, Version=1.2.0.200, Culture=neutral, PublicKeyToken=764d581291d764f7' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)** at x.Foo.FooGO() at x.Foo.Foo2(String groupName_) in Foo.cs:line 123 at x.Foo.UnitTests.FooTests.TestFoo() in FooTests.cs:line 98** System.IO.FileLoadException: Could not load file or assembly 'Utility, Version=1.2.0.203, Culture=neutral, PublicKeyToken=764d581291d764f7' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)  I look in my references, and I only have a reference to Utility version 1.2.0.203 (the other one is old). Any suggestions on how I figure out what is trying to reference this old version of this DLL file? Besides, I don't think I even have this old assembly on my hard drive. Is there any tool to search for this old versioned assembly?
67365
How to implement Unit Test at Unity3D.   I wonder if it would be possible to extend the Unity editor to have some sort of testing framework in it.    Is there any guideline to implement it? Any reference like book, blog? Any working example or project?
73868
I need help. I am currently trying to test this code before uploading  public class CoreValuesExt { ApexPages.StandardController sc; public boolean readonly {get; set;} public Core_Values__c cv {get; set;} public integer countEdit = 1; public string buttonValue {get; set;} public integer recordScan;  public CoreValuesExt(ApexPages.StandardController sc) {     this.sc = sc;     cv = new Core_Values__c();     cv.Account__c = sc.getid();      readonly = true;     buttonValue = 'Edit';     recordScan = [SELECT COUNT() FROM Core_Values__c WHERE Account__c = :cv.Account__c];    if (recordScan != 0){    cv = [SELECT id, HSE__c, Professionalism_Integrity__c, Quality_Accuracy__c, Technology_Innovation__c, Timeliness__c, Value_for_money__c FROM Core_Values__c WHERE Account__c = :cv.Account__c];     }  }  public ApexPages.PageReference Save() {     return sc.Save(); }  public void ApplyAction() {     countEdit++;     Integer modolus = Math.mod(countEdit, 2);     String total = cv.HSE__c + cv.Professionalism_Integrity__c + cv.Quality_Accuracy__c + cv.Technology_Innovation__c + cv.Value_for_Money__c + cv.Timeliness__c;     if(modolus == 0)     {         readonly = false;         buttonValue = 'Save';     }     else     {         if(total != 'nullnullnullnullnullnull')            {         if (recordScan == 0){         insert cv;         readonly = true;         buttonValue = 'Edit';         }         else         {         update cv;         readonly = true;         buttonValue = 'Edit';         }         }     }    }   }  With this trigger.  trigger CoreValuesTrigger on Core_Values__c (before insert) {  Core_Values__c cvs = Trigger.new; CoreValuesExt.ApplyAction(cvs);  }   But when I try to save, I get a message saying:      Illegal assignment from List to   CoreValuesExt__Core_Values__c at line 3 column 1   "  How do I go through with this? I need help. Thanks
92800
For a given class I would like to have tracing functionality i.e. I would like to log every method call (method signature and actual parameter values) and every method exit (just the method signature).      How do I accomplish this assuming that:     I don't want to use any 3rd party AOP libraries for C#, I don't want to add duplicate code to all the methods that I want to trace,   I don't want to change the public API of the class - users of the class should be able to call all the methods in exactly the same way.     To make the question more concrete let's assume there are 3 classes:     public class Caller   {      public static void Call()       {          Traced traced = new Traced();          traced.Method1();          traced.Method2();       }  }   public class Traced   {      public void Method1(String name, Int32 value) { }       public void Method2(Object object) { }  }   public class Logger  {      public static void LogStart(MethodInfo method, Object[] parameterValues);       public static void LogEnd(MethodInfo method);  }   How do I invoke Logger.LogStart and Logger.LogEnd for every call to Method1 and Method2 without modifying the Caller.Call method and without adding the calls explicitly to Traced.Method1 and Traced.Method2?  Edit:  What would be the solution if I'm allowed to slightly change the Call method?
6182
I have written the following batch apex class and corresponding test class. Tests are successful but the execute method is never called. I have attempted to debug to try to pinpoint the problem but have had no luck.   Batch Class  global class BatchAddToCampaign implements Database.Batchable&lt;sObject&gt;,  Database.Stateful {     global final Id campaignId;     global final Set&lt;Id&gt; qKeys;      global BatchAddToCampaign(Id campaignId, Set&lt;Id&gt; qKeys){         this.campaignId = campaignId;         this.qKeys = qKeys;     System.Debug('this.campaignId is ' + campaignId);              System.Debug('this.qkeys is ' + qKeys);                       }      global Database.QueryLocator start(Database.BatchableContext BC) {         return Database.getQueryLocator('Select Id From Lead Where Id In :qKeys');     }      global void execute(Database.BatchableContext BC, List&lt;Lead&gt; scope) {         System.Debug('Starting Execute Method!');                  Integer collsize;          List&lt;CampaignMember&gt; cm = new List&lt;CampaignMember&gt;();            Map&lt;Id, Campaign&gt; cmMap = new Map&lt;Id, Campaign&gt;([Select (Select LeadId From CampaignMembers) From Campaign c Where Id = :campaignId]);          for(Lead myLeads : scope) {              CampaignMember newCM = new CampaignMember(              CampaignId = campaignId,              LeadId = myLeads.Id,              status = 'Added' );                   if (!cmMap.containsKey(myLeads.Id)) {                      cm.add(newCM);                       collsize = cm.size();                  }          }           try {              Database.insert(cm);           } catch (DmlException ex) {             System.Debug('Insert failed ' + ex);          }             }      global void finish(Database.BatchableContext BC) {         AsyncApexJob a = [SELECT Id, Status, NumberOfErrors, JobItemsProcessed,  TotalJobItems, CreatedBy.Email From AsyncApexJob Where Id = :BC.getJobId()];         // Send an email to the Apex job's submitter notifying of job completion.         Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();         String[] toAddresses = new String[] {a.CreatedBy.Email};         mail.setToAddresses(toAddresses);         mail.setSubject('Add to Campaign ' + a.Status);         String campaignURL = URL.getSalesforceBaseUrl().toExternalForm() + '/' + campaignId;         mail.setPlainTextBody('The batch Apex job processed ' + a.TotalJobItems + ' batches with '+ a.NumberOfErrors + ' failures. ' + 'Link to Campaign: ' + campaignURL);         Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });     } }   Test Class  @isTest public class BatchAddToCampaignTest {     static testMethod void testMethod1()     {         List&lt;Lead&gt; lstCM= new List&lt;Lead&gt;();         for(Integer i=0 ;i &lt;1;i++){             Lead myLead = new Lead();             myLead.Id = '00Q1U00000KqFcDUAV';             lstCM.add(myLead);             Integer collSize = lstCM.size();              System.debug('List Collection Size is ' + collSize);                 {                  System.debug('Start Set');                 Set&lt;Id&gt; leadIds = (new Map&lt;Id,SObject&gt;(lstCM)).keySet();                 System.debug('End Set');                 Integer collSizeSet = leadIds.size();                  System.debug('Set Collection Size is ' + collSizeSet);                 Id workingCampaignId = '7011U000000RWRAQA4';                  Test.startTest();                  //BatchAddToCampaign ba = new BatchAddToCampaign(workingCampaignId, leadIds);                 DataBase.executeBatch(new BatchAddToCampaign(workingCampaignId, leadIds));                  Test.stopTest();                   }             }      } }
7725
I'm building a class library that will have some public &amp; private methods. I want to be able to unit test the private methods (mostly while developing, but also it could be useful for future refactoring).  What is the correct way to do this?
82873
I am trying to learn how to do APEX testing but all the tests in the documentation are too complex and I can't find an example of a simple APEX Controller that is a Hello World Test.  I have this APEX Code  public class MessageMaker{ public static string helloMessage() {     return('You say "Goodbye," I say "Hello"');     } }   Should I be testing that the String is the same? Here is my test that doesn't work      @isTest public class MessageMakerTest {     public static testMethod void testMyClass(){         MessageMaker controller = new MessageMaker();         String helloMessage = helloMessage();          System.assertEquals(helloMessage, 'You say "Goodbye," I say "Hello"');      } }   I am getting this error.       Method does not exist or incorrect signature: helloMessage()   I have some more advanced APEX code but I want to understand what I need to test for and how before I can do that.  Thank you in advance.
86355
My team is responsible for the development of an API for a large system that we also write. We need to provide example code so that other developers using our API can learn how to use it. We have been documenting the code using the xml document comments. eg.  /// &lt;summary&gt;Summary here&lt;/summary&gt; /// &lt;example&gt;Here is an example  &lt;code&gt;example code here&lt;/code&gt; &lt;/example&gt; public void SomeFunction()    We then use Sandcastle and build the help files we need (chm and an online website).  It is quite embarrassing when the example code doesnt work, and this is usually because some functionality has changed or a simple error.  Has anyone ever done something like this, but also configured unit tests to run on the example code so that they are known to work during the build?
107559
I am adding cookie to my page in the controller using  ApexPages.currentPage().setCookies(new Cookie[]{CookieName});  When am trying to get the code coverage, my test class is not covering the above line.  How to get the code coverage for the above setcookie method in the test class.
79960
I am unit testing a .NET application (.exe) that uses an app.config file to load configuration properties.  The unit test application itself does not have an app.config file.    When I try to unit test a method that utilizes any of the configuration properties, they return null.  I'm assuming this is because the unit test application is not going to load in the target application's app.config.  Is there a way to override this or do I have to write a script to copy the contents of the target app.config to a local app.config?     post kind-of asks this question but the author is really looking at it from a different angle than I am.  EDIT: I should mention that I'm using VS08 Team System for my unit tests.
26861
How can I test the below controller and get greater than 0% coverage?  My controller class looks like this:  public with sharing class EmployeeController  {     public EmployeeController(ApexPages.StandardController controller)     {      }      public PageReference pdf1()     {          return Page.Employee_PDF;     }         public list&lt;Certification__c&gt; certification      {         get         {                 certification = [SELECT Date_Certified__c, Name, Principle__c, Year_Certified__c FROM Certification__c WHERE Employee__c =:ApexPages.CurrentPage().getparameters().get('id')];                 return certification;         }         set;      }      public list&lt;Project_Experience__c&gt; proj         {                 get                 {                         proj = [SELECT Client__c, Duration__c, Location__c, Position__c, Project_Description__c, Project_Name__c, Responsibilities__c FROM Project_Experience__c WHERE Employee__c =:ApexPages.CurrentPage().getparameters().get('id')order by Project_End_Date__c desc];                         return proj;                 }                 set;         }      public list&lt;Training__c&gt; training     {         get         {                 training =[SELECT Location__c, Name, Principle__c, Trainer__c, Year__c FROM Training__c WHERE Employee__c =:ApexPages.CurrentPage().getparameters().get('id')];                 return training;         }         set;     }          public list&lt;Employee__c&gt; emp         {                 get                 {                         emp = [SELECT Name, Sex__c, Foreign_Language_Proficiency__c, Nationality__c, Qualifications__c, Tools__c FROM Employee__c where Id = :ApexPages.CurrentPage().getparameters().get('id') ];                         return emp;                 }                 set;         }    }   Here is my current test class:  @isTest private class EmployeeControllerTestClass2 {     static testMethod void myUnitTest()      {        Employee__c emp = new Employee__c(Name = 'empTest',Employee_Status__c='Active' );         insert emp;          Project_Experience__c project = new Project_Experience__c (Employee__c = emp.id, Project_Name__c='Indosat');         insert project;         Training__c training = new Training__c (Employee__c = emp.id, Name='Salesforce Adm 201');        insert training;           PageReference pageRef = Page.Employee_Pages;         Test.setCurrentPage(pageRef);         ApexPages.Standardcontroller sc = new ApexPages.Standardcontroller(emp);         ApexPages.currentPage().getParameters().put('Id',emp.id);          Test.StartTest();     } }
48883
I've just started playing with Guice, and a use-case I can think of is that in a test I just want to override a single binding.  I think I'd like to use the rest of the production level bindings to ensure everything is setup correctly and to avoid duplication.  So imagine I have the following Module  public class ProductionModule implements Module {     public void configure(Binder binder) {         binder.bind(InterfaceA.class).to(ConcreteA.class);         binder.bind(InterfaceB.class).to(ConcreteB.class);         binder.bind(InterfaceC.class).to(ConcreteC.class);     } }   And in my test I only want to override InterfaceC, while keeping InterfaceA and InterfaceB in tact, so I'd want something like:  Module testModule = new Module() {     public void configure(Binder binder) {         binder.bind(InterfaceC.class).to(MockC.class);     } }; Guice.createInjector(new ProductionModule(), testModule);   I've also tried the following, with no luck:  Module testModule = new ProductionModule() {     public void configure(Binder binder) {         super.configure(binder);         binder.bind(InterfaceC.class).to(MockC.class);     } }; Guice.createInjector(testModule);   Does anyone know if it's possible to do what I want or am I completely barking up the wrong tree??  --- Follow up: It would seem I can achieve what I want if I make use of the @ImplementedBy tag on the interface and then just provide a binding in the test case, which works nicely when there is a 1-1 mapping between the interface and implementation.  Also, after discussing this with a colleague it would seem we'd head down the road of overriding an entire module and ensuring we have our modules defined correctly.  This seems like it might cause a problem though where a binding is misplaced in a module and needs to be moved, thus possibly breaking a load of tests as bindings may no longer be available to be overriden.
53785
So, every time I have written a lambda expression or anonymous method inside a method that I did not get quite right, I am forced to recompile and restart the entire application or unit test framework in order to fix it. This is seriously annoying, and I end up wasting more time than I saved by using these constructs in the first place. It is so bad that I try to stay away from them if I can, even though Linq and lambdas are among my favourite C# features.  I suppose there is a good technical reason for why it is this way, and perhaps someone knows? Furthermore, does anyone know if it will be fixed in VS2010?  Thanks.