How to debug Nunit test with VS 2010 sp1? - nunit

namespace MoqSample.Test
{
[TestFixture]
public class GivenCustomerServiceTest
{
private ICustomerService customerService;
private CustomerModel customer;
// Defining the mock object.
private Mock<ICustomerRepository> mockCustomerRepository;
[SetUp]
public void SetUp()
{
//Creating the mock object.
mockCustomerRepository = new Mock<ICustomerRepository>();
customerService = new CustomerService(mockCustomerRepository.Object);
}
[Test]
public void GetCustomerByIdTest()
{
customer = new CustomerModel { Id = 1, Name = "TEST-CUSTOMER", Address = "abc" };
mockCustomerRepository.Setup(customerRepository => customerRepository.GetCustomerById(1)).Returns(customer);
var customerReturned = customerService.GetCustomerById(1);
//Verifying values.
Assert.AreEqual(customer.Id, customerReturned.Id);
Assert.AreEqual(customer.Name, customerReturned.Name);
Assert.AreEqual(customer.Address, customerReturned.Address);
}
}
}
When I am trying to debug the code in aforementioned class , it's not hitting the break point.
I.e I am unable to debug the code.
Any suggestions are welcome.

Using the Resharper or TestDriven test runners should allow you to debug through your unit tests.

Related

Roslyn codefix and fixall action not executed properly under unit test

I've 'successfully' written a CodeFix and FixAllProvider, BUT...
The diagnostic I'm trying to handle can occur multiple times in the same document on the same line. However, the behavior under unit test (CSharpCodeFixTest) stumps me.
If a test generates only one instance of the diagnostic, CSharpCodeFix<> calls the CodeFix initially then calls the FixAllProvider multiple times during Verification. The test succeeds.
If a test generates more than one diagnostic, CSharpCodeFix<> calls the CodeFix once. CSharpCodeFix<> never calls the FixAllProvider, and since the CodeFix cannot fix all instances. the test fails the before/after document comparison.
Note that in these samples, namespaces (not shown) disambiguate the classes from their bases. I've removed the fix implementations because I believe them irrelevant to the problem.
First the CodeFix
[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(CodeFixProvider)), Shared]
public class CodeFixProvider : Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider
{
public sealed override ImmutableArray<string> FixableDiagnosticIds
{
get { return ImmutableArray.Create(EGNT0003NoInlineInstantiationAnalyzer.DiagnosticId); }
}
public sealed override Microsoft.CodeAnalysis.CodeFixes.FixAllProvider GetFixAllProvider()
{
Microsoft.CodeAnalysis.CodeFixes.FixAllProvider provider = FixAllProvider.Instance;
return provider;
}
public static readonly string EquivalenceKey = "EG0003CodeFixProvider";
public sealed override Task RegisterCodeFixesAsync(CodeFixContext context)
{
foreach (Diagnostic diagnostic in context.Diagnostics.Where(d => FixableDiagnosticIds.Contains(d.Id)))
{
context.RegisterCodeFix(CodeAction.Create(title: "Introduce local variable",
token => GetTransformedDocumentAsync(context.Document, diagnostic, token),
equivalenceKey: EquivalenceKey), diagnostic);
}
return Task.CompletedTask;
}
;
Here is the FixAllProvider
public sealed class FixAllProvider : Microsoft.CodeAnalysis.CodeFixes.FixAllProvider
{
private FixAllProvider()
{
}
private static readonly Lazy<FixAllProvider> lazy = new Lazy<FixAllProvider>(() => new FixAllProvider());
public static FixAllProvider Instance
{
get
{
return lazy.Value;
}
}
public override IEnumerable<string> GetSupportedFixAllDiagnosticIds(Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider originalCodeFixProvider)
{
string[] diagnosticIds = new[]
{
EGNT0003NoInlineInstantiationAnalyzer.DiagnosticId,
};
return diagnosticIds;
}
public override async Task<CodeAction> GetFixAsync(FixAllContext fixAllContext)
{
:
Finally here is the CodeAction invoked by the FixAllProvider.
public class FixAllCodeAction : CodeAction
{
private readonly List<KeyValuePair<Document, ImmutableArray<Diagnostic>>> _diagnosticsToFix;
private readonly Solution _solution;
public FixAllCodeAction(string title, Solution solution, List<KeyValuePair<Document, ImmutableArray<Diagnostic>>> diagnosticsToFix)
{
this.Title = title;
_solution = solution;
_diagnosticsToFix = diagnosticsToFix;
}
public override string Title { get; }
public override string EquivalenceKey => "EG0003CodeFixProvider";
protected override async Task<Solution> GetChangedSolutionAsync(CancellationToken cancellationToken)
{
Solution newSolution = _solution;
:
I've debugged through CSharpCodeFixTest<> and continue to do so. I'm hoping someone has seen this issue before and can see my mistake.
I expected to see the code fix tests to complete successfully. I verified through other means that the documents produced by the CodeFix and the FixAllProvider are valid and correct.

Autofac: cannot resolve dependency using factory after ContainerBuilder.Update()

My problem is that I want to use Func<> factory to resolve dependency. And in if I use ContainerBuilder Update() (I need it for mocking some services in integration tests), this factories still resolve outdated instances.
I created simple scenario to reproduce the problem:
class Program
{
static void Main(string[] args)
{
var containerBuilder = new ContainerBuilder();
containerBuilder.RegisterType<Test>().As<ITest>();
containerBuilder.RegisterType<Test1Factory>().As<ITestFactory>();
containerBuilder.RegisterType<TestConsumer>().AsSelf();
var container = containerBuilder.Build();
var tc1 = container.Resolve<TestConsumer>();
var cbupdater = new ContainerBuilder();
cbupdater.RegisterType<Test2>().As<ITest>();
cbupdater.RegisterType<Test2Factory>().As<ITestFactory>();
cbupdater.Update(container);
var tc2 = container.Resolve<TestConsumer>();
Console.ReadLine();
}
}
public interface ITest
{
int Id { get; set; }
}
public class Test : ITest
{
public Test()
{
Id = 1;
}
public int Id { get; set; }
}
public class Test2 : ITest
{
public Test2()
{
Id = 2;
}
public int Id { get; set; }
}
public interface ITestFactory
{
ITest Create();
}
public class Test1Factory : ITestFactory
{
public ITest Create()
{
return new Test();
}
}
public class Test2Factory : ITestFactory
{
public ITest Create()
{
return new Test2();
}
}
public class TestConsumer
{
public TestConsumer(Func<ITest> testFactory, ITest test, ITestFactory customFactory)
{
Console.WriteLine("factory: " + testFactory().Id);
Console.WriteLine("direct: " + test.Id);
Console.WriteLine("MyCustomFactory: " + customFactory.Create().Id);
Console.WriteLine("*************");
Console.WriteLine();
}
}
The output is:
factory: 1 direct: 1 MyCustomFactory: 1
factory: 1 direct: 2 MyCustomFactory: 2
Notice "factory: 1" in both cases.
Am I missing something or I have to create my cusom factory in this scenario?
P.S.
Autofac 3.5.2 or 4.0 beta 8-157
.net 4.5.1
That's by design unfortunately, the reasons, I don't know. Looking at the Autofac code gives you a better insight on how they register items with the same interface definition, in short, all registrations are maintained but the last registration wins (ref). Wait...that's not all, weirdly, for Fun<...>, you actually get them in order. You can easily test by changing the constructor of the TestConsumer class to:
public TestConsumer(Func<ITest> testFactory, IEnumerable<Func<ITest>> testFactories, IEnumerable<ITest> tests, ITest test, ITestFactory customFactory)
{
// ...
}
Note that you get all the Funcs and the ITest registration. You are simply lucky that resolving ITest directly resolves to Test2.
Now, having said all of the above, there is a way described here. You have to create a container without the registration you want to override, therefore:
/// <summary>
/// This has not been tested with all your requirements
/// </summary>
private static IContainer RemoveOldComponents(IContainer container)
{
var builder = new ContainerBuilder();
var components = container.ComponentRegistry.Registrations
.Where(cr => cr.Activator.LimitType != typeof(LifetimeScope))
.Where(cr => cr.Activator.LimitType != typeof(Func<ITest>));
foreach (var c in components)
{
builder.RegisterComponent(c);
}
foreach (var source in container.ComponentRegistry.Sources)
{
builder.RegisterSource(source);
}
return builder.Build();
}
And you can simply change your main method to the following:
static void Main(string[] args)
{
var containerBuilder = new ContainerBuilder();
containerBuilder.RegisterType<Test>().As<ITest>();
containerBuilder.RegisterType<Test1Factory>().As<ITestFactory>();
containerBuilder.RegisterType<TestConsumer>().AsSelf();
var container = containerBuilder.Build();
var tc1 = container.Resolve<TestConsumer>();
container = RemoveOldComponents(container);
var cbupdater = new ContainerBuilder();
cbupdater.RegisterType<Test2>().As<ITest>();
cbupdater.RegisterType<Test2Factory>().As<ITestFactory>();
cbupdater.Update(container);
var tc2 = container.Resolve<TestConsumer>();
Console.ReadLine();
}
PS: Wouldn't it be great to have a method which does the exact opposite of PreserveExistingDefaults()

How do I pass an Action into a TestCase

I have an NUnit test
[TestCase(...)]
public void test_name(Action onConfirm)
{
...
}
What I want to do is pass an Action into this test in the TestCase attribute, but no matter what I try keeps failing. I tried to put
() => SomeDummyMethodIDefined()
directly into the TestCase and that didn't work.
I created an Action
Action DummyAction = () => SomeDummyMethodIDefined();
and pass DummyAction into the TestCase and that didn't work.
Is there a way to do this?
This is a very rough example which I was inspired from reading the NUnit docs here
namespace NUnitLambda
{
using System;
using NUnit.Framework;
[TestFixture]
public class Class1
{
[Test]
[TestCaseSource(typeof(SourceClass), "TestCases")]
public void Foo(Action action)
{
action();
}
}
public class SourceClass
{
private static Action t = () => Console.WriteLine("Hello World");
public static Action[] TestCases = { t };
}
}
Have a play around with the code, hopefully you will get what you want out of it. For the record, I was using NUnit 2.6.
EDIT:
You don't have to use static here either e.g.
public class SourceClass
{
private Action t = () => Console.WriteLine("Hello World");
public Action[] TestCases;
public SourceClass()
{
TestCases = new Action[1];
TestCases[0] = t;
}
}

testing controller using MOQ calling repository

I'm very new to Mocking. In the below example i'm using Moq and trying to create a _companyRepository. However the second test has a null ref. ie Company is not instantiated.
Assert.AreEqual(viewModel.Company.Name, "MyCompany");
Think i'm missing something silly here.
[TestClass]
public class ErrorControllerTest
{
private Mock<ICompanyRepository> _companyRepository;
public ErrorController CreateErrorController()
{
_companyRepository = new Mock<ICompanyRepository>();
_companyRepository.Setup(c => c.Get(2)).Returns(new Company {Name = "MyCompany"});
return new ErrorController(_companyRepository.Object);
}
[TestMethod]
public void Test()
{
var controller = CreateErrorController();
controller.Test(""); // action is called
var viewModel = (ErrorViewModel)controller.ViewData.Model;
Assert.IsInstanceOfType(controller.ViewData.Model, typeof(ErrorViewModel));
Assert.AreEqual(viewModel.Company.Name, "MyCompany");
}
}
controller
public class ErrorController : Controller
{
private readonly ICompanyRepository _companyRepository;
public ErrorController(ICompanyRepository companyRepository)
{
_companyRepository = companyRepository;
}
public ActionResult Test()
{
var company = _companyRepository.Get(2);
var viewModel = new ErrorViewModel
{
Company = company
};
return View(viewModel);
}
}
this works.... Guess i didn't compile everything. Very dumb.
Tho am i doing this the right way. Appreciate any comments.

Why does MSTest and TestDriven.NET behave differently using this code?

Check out this code:
internal static readonly Dictionary<Type, Func<IModel>> typeToCreator = new Dictionary<Type, Func<IModel>>();
protected static object _lock;
public virtual void Register<T>(Func<IModel> creator)
{
lock (_lock)
{
if (typeToCreator.ContainsKey(typeof(T)))
typeToCreator[typeof(T)] = creator;
else
typeToCreator.Add(typeof(T), creator);
}
}
When I use run the code in this test (testframework is MSTest):
[TestMethod]
public void Must_Be_BasePresenterType()
{
var sut = new ListTilbudPresenter(_tilbudView);
Assert.IsInstanceOfType(sut, typeof(BasePresenter));
}
...MSTest passes it and TestDriven.NET fails it because _lock is null.
Why does MSTest NOT fail the test???