How to write Unit Test for code that uses IOwinContext extension methods - nunit

IdentityServer3 has a lot extension methods, which are nice to have. The problem arises when trying to unit test the code that has some of these IOwinContext extension method calls like: GetIdentityServerHost(), GetIdentityServerBasePath() etc. from this class.
Even after mocking HttpContext and being able to get a OwinContext instance, I still get errors because since everything is a mock, so internal dependencies (e.g Autofac based) are not resolved.
Below is a unit test error:
System.ArgumentNullException : Value cannot be null.
Parameter name: context
at Autofac.ResolutionExtensions.ResolveOptionalService(IComponentContext context, Service service, IEnumerable'1 parameters) in c:\ballen\github\identity\IdSrv3\IdentityServer3\source\Core\Internal\AntiXssLibrary\UnicodeCharacterEncoder.cs:line 0
at IdentityServer3.Core.Extensions.InternalOwinExtensions.ResolveDependency(IOwinContext context, Type type) in c:\ballen\github\identity\IdSrv3\IdentityServer3\source\Core\Extensions\InternalOwinExtensions.cs:line 78
at IdentityServer3.Core.Extensions.InternalOwinExtensions.ResolveDependency[T](IOwinContext context) in c:\ballen\github\identity\IdSrv3\IdentityServer3\source\Core\Extensions\InternalOwinExtensions.cs:line 70
at IdentityServer3.Core.Extensions.OwinEnvironmentExtensions.GetIdentityServerIssuerUri(IDictionary'2 env) in c:\ballen\github\identity\IdSrv3\IdentityServer3\source\Core\Extensions\OwinEnvironmentExtensions.cs:line 672
Has anyone got around this, or you just skip writing test for such classes? - Here come the bullets! I know its bad to skip tests, but I am on the verge of giving up trying.

Related

How to call constructor with interface arguments when mocking a concrete class with Moq

I have the following class, which uses constructor injection:
public class Service : IService
{
public Service(IRepository repository, IProvider provider) { ... }
}
For most methods in this class, I simply create Moq mocks for IRepository and IProvider and construct the Service. However, there is one method in the class that calls several other methods in the same class. For testing this method, instead of testing all those methods together, I want to test that the method calls those methods correctly and processes their return values correctly.
The best way to do this is to mock Service. I've mocked concrete classes with Moq before without issue. I've even mocked concrete classes that require constructor arguments with Moq without issue. However, this is the first time I've needed to pass mocked arguments into the constructor for a mocked object. Naturally, I tried to do it this way:
var repository = new Mock<IRepository>();
var provider = new Mock<IProvider>();
var service = new Mock<Service>(repository.Object, provider.Object);
However, that does not work. Instead, I get the following error:
Castle.DynamicProxy.InvalidProxyConstructorArgumentsException : Can not instantiate proxy of class: My.Namespace.Service.
Could not find a constructor that would match given arguments:
Castle.Proxies.IRepository
Castle.Proxies.IProvider
This works fine if Service's constructor takes simple arguments like ints and strings, but not if it takes interfaces that I'm mocking. How do you do this?
Why are you mocking the service you are testing? If you are wishing to test the implementation of the Service class (whether that be calls to mocked objects or not), all you need are mocks for the two interfaces, not the test class.
Instead of:
var repository = new Mock<IRepository>();
var provider = new Mock<IProvider>();
var service = new Mock<Service>(repository.Object, provider.Object);
Shouldn't it be this instead?
var repository = new Mock<IRepository>();
var provider = new Mock<IProvider>();
var service = new Service(repository.Object, provider.Object);
I realize that it is possible to mock concrete objects in some frameworks, but what is your intended purpose? The idea behind mocking something is to remove the actual implementation so that it does not influence your test. But in your question, you have stated that you wish to know that certain classes are called on properly, and then you wish to validate the results of those actions. That is undoubtedly testing the implementation, and for that reason, I am having a hard time seeing the goals of mocking the concrete object.
I had a very similar problem when my equivalent of Service had an internal constructor, so it was not visible to Moq.
I added
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
to my AssemblyInfo.cs file for the implementing project. Not sure if it is relevant, but I wanted to add a suggestion on the off chance that it helps you or someone else.
It must be old version issue, all is ok with latest version. Nick, Please check!
P.s.: I started bounty by misstake (I had wrong signature in my constructor).

Glimpse ADO fails in Web Site project with TableAdapters - Part 2

This is a follow up to this problem.
That problem was fixed. However, new compiler errors occurred. The compiler errors indicate the following:
The Glimpse.Ado.AlternateType.GlimpseDbCommand class needs a default constructor
The Glimpse.Ado.AlternateType.GlimpseDbConnection class needs a constructor that takes a string (connectionString)
This second problem is strange, because the System.Common.DbConnection class does not have a constructor that takes a string either.

How to make JUnit annotations work in SOAP UI?

I am trying to port my JUnit test scripts into SOAP UI. Since SOAP UI supports Java, I thought it will support JUnit as well. I have placed the JUnit Jar in 'ext' folder. When I run the test, I could see that the annotation #Test is not being recognized by SOAP UI.
I got the below error:
Script1.groovy: 9: Invalid constructor format. Remove 'void' as the
return type if you want a constructor, or use a different name if you
want a method. at line: 9 column: 4. File: Script1.groovy # line 9,
column 4.
#Test
Am I doing it entirely wrong?
Without seeing your code (since it hasn't been posted as of writing this), you probably don't need to have a return type of void, especially on the constructor.
I'm still a little confused by your question though; are you trying to run JUnit from inside of SoapUI (it appears that way from the error message you are getting) or do you want to run it from a Java class, using JUnit and calling SoapUI. If you are doing the latter, try the following example of the format that should work:
public class CalculatorServiceTestCase {
#Test
public void testCalculatorService() throws Exception {
SoapUITestCaseRunner testCaseRunner = new SoapUITestCaseRunner();
SoapUIMockServiceRunner mockServiceRunner = new SoapUIMockServiceRunner();
testCaseRunner.setProjectFile("src/test/resources/calculator-soapui-project.xml");
mockServiceRunner.setProjectFile("src/test/resources/calculator-soapui-project.xml");
mockServiceRunner.run();
testCaseRunner.run();
}
}

Model is not automatically validated when unit testing

Here's part of a controller action:
[HttpPost]
public ActionResult NewComplaint(Complaint complaint)
{
if(!ModelState.IsValid)
{
// some code
}
// some more code...
}
When running the application, the model is automatically validated before the if statement is even called. However, when attempting to unit test this code, the automatic validation does not occur.
If I were to use a FormCollection and call TryUpdateModel instead, the validation would occur but I don't want to use that.
I've found that calling TryValidateModel(model) before the if statement works around the problem well; only requiring one extra line of code. I'd rather get rid of it however.
Any ideas why the automatic validation does not occur when unit testing but occurs when the application is running?
EDIT: Forgot to mention, I'm using ASP.NET MVC3 RC1 and I'm mocking the HTTPContext object of the controller if that makes any difference
Validation occurs during model binding (and TryUpdateModel performs model binding).
But I think the problem is that what you are trying to test is the MVC framework (i.e. the fact that validation occurs before an action method is invoked). You shouldn't test that.
You should assumet that that part just works (because we test it extensively) and only test your application code. So in this case, the only thing you need to mock is the return value of ModelState.IsValid and you can do that by adding a validation error manually:
ModelState.AddModelError("some key", "some error message")

Unit tests with mock verifies

I have a unit test that
creates a mock
calls my method to be tested (also injecting my mock)
asserts method results
verifies mock calls
When mock calls don't verify as expected I get an exception, thus failing a test.
How should I correctly call this verifies? Should I just be calling
// verify property get accessor call
m.VerifyGet<bool>(p => p.IsRead, Times.AtLeastOnce());
or should I call it with Assert
// verify property get accessor call
Assert.DoesNotThrow(() => m.VerifyGet<bool>(p => p.IsRead, Times.AtLeastOnce()));
When verify fails I get an exception anyway.
What's the proper way of mock verifying?
VerifyGet is enough, assert seems to add no value so why add more verbiage?
The DoesNotThrow-method should be used to test whether your own methods adhere to your specifications.
In short, adding the DoesNotThrow looks like you're testing the behaviour of VerifyGet instead of the behaviour of your SUT.
Of course, you can wrap it around the VerifyGet, but I think that only makes things confusing since VerifyGet would fail the test anyway.