Moles appears to require moled methods to be hashed - visual-studio-2010

I am trying out Moles on a home project to (hopefully) be able to recommend that it be adopted in projects at work. I am working with VS 10.0.30319 and Moles 1.0.0.0.
I have created the following class:
public class DeveloperTestControlBL
{
public static bool VerifyCurrentDevelopmentStatus(int tpid, int testStatusID)
{
return false; // For this example, always return false,
// so that a return of true means the delegation worked
}
}
In my test class, I have created a test which tests a class which calls the VerifyCurrentDevelopmentStatus method. I would have expected to have a declaration of the form:
[TestMethod]
[HostType("Moles")]
public void TestPreTCIToEditReady_WithMoles()
{
var devTCBL = new SDeveloperTestControlBL();
devTCBL.VerifyCurrentDevelopmentStatus = delegate(int tpid, int testStatusID)
{
return true;
}
// rest of the test here
}
What I have found is that to set the delegate I have to do this:
[TestClass]
public class MyTest
{
[TestMethod]
[HostType("Moles")]
public void TestPreTCIToEditReady_WithMoles()
{
DelegateExample.Moles.MDeveloperTestControlBL.VerifyCurrentDevelopmentStatusInt32Int32 =
VerifyCurrentDevelopmentStatusAlwaysTrue;
// Rest of the test here
}
private bool VerifyCurrentDevelopmentStatusAlwaysTrue(int tpid, int status)
{
return true;
}
Does anyone have any advice as to what I am doing incorrectly? I have the
using Microsoft.Moles.Framework; statement and have a reference to DeveloperTestControlBL.Moles in the test project.
Thanks in advance,
Ron L

Try this
devTCBL.VerifyCurrentDevelopmentStatus (delegate(int tpid, int testStatusID)
{
return true;
});
It worked for me.

Related

How to write test code for Web API in Visual Studio?

I'm a bit new to test project. I currently have a web api project which contains Get, Put, Post and Delete methods. When comes to writing test cases, I'm confused. Should I write test code to test the Http URL?
My web api code:
// GET api/values/5
[HttpGet("{id}")]
public IActionResult Get(string id)
{
using (var unitOfWork = new UnitOfWork(_db))
{
var r = unitOfWork.Resources.Get(id);
unitOfWork.Complete();
Models.resource result = ConvertResourceFromCoreToApi(r);
if (result == null)
{
return NotFound();
}
else
{
return Ok(result);
}
}
}
And in my test project, I kind of stuck here. We are using Xunit. How to write test code to test the Get method? Or should I write code to test the URL api/values/5 instead, but how?
[Fact]
public void GetTest()
{
using (var unitOfWork = new UnitOfWork(new MockDatabase()))
{
}
}
Any help would be appreciated.
You need to make a couple of changes before you can really unit test your controller. You need to pass an instance of your UnitOfWork class into the controller in its constructor. Then your controller method code becomes:
// GET api/values/5
[HttpGet("{id}")]
public IActionResult Get(string id)
{
var r = unitOfWork.Resources.Get(id);
unitOfWork.Complete();
Models.resource result = ConvertResourceFromCoreToApi(r);
if (result == null)
{
return NotFound();
}
else
{
return Ok(result);
}
Then in your unit tests you do this:
[Fact]
public void GetTest()
{
// Arrange
// You really want to mock your unit of work so you can determine
// what you are going to send back
var unitOfWork = new MockUnitOfWork();
var systemUnderTest = new Controller(unitOfWork);
system.Request = new HttpRequestMessage();
// Act
var result = systemUnderTest.Get(1);
// Assert
// Here you need to verify that you got back the expected result
}
Injecting the UnitOfWork class into the controller is probably another question. Mark Seemann has an excellent post on the subject, but it might be a little advanced. There are a number of different ways to accomplish that with simpler (but maybe not as robust methods). Google is your friend with that. But if you have questions, post another question.
Hope that helps.
You would need to make some design changes to your controller to make it easy to test. In your action you are creating an instances which will make it difficult to test with a fake dependencies to the controller. Also your controller should depend on abstractions rather than concretions which will allow the controller to be more testable.
public class MyWebApiController : ApiController {
private IUnitOfWork unitOfWork;
public MyWebApiController(IUnitOfWork unitOfWork) {
this.unitOfWork = unitOfWork;
}
// GET api/values/5
[HttpGet("{id}")]
public IActionResult Get(string id) {
var r = unitOfWork.Resources.Get(id);
unitOfWork.Complete();
Models.resource result = ConvertResourceFromCoreToApi(r);
if (result == null) {
return NotFound();
} else {
return Ok(result);
}
}
//...other code
}
Notice the controller uses dependency injection to inject an IUnitOfWork. That makes the controller more testable, because you can inject mocks of its dependencies when unit testing.
From there it is just to create an instance of the controller and call the method under test with mocks of the dependencies.
[Fact]
public void GetTest() {
//Arrange (Setup the parts needed to run test)
var unitOfWork = new MockUnitOfWork(new MockDatabase());
//Or using your mocking framework of choice
//var unitOfWork = Mock.Of<IUnitOfWork>(); //this is using Moq
var controller = new MyWebApiController(unitOfWork);
var id = "Test Id value here";
//Act (call the method under test)
var result - controller.Get(id);
//Assert (check results)
//...Do your assertion pertaining to result of calling method under test
}
Reference : Unit Testing Controllers in ASP.NET Web API 2

How to write unit test for HttpContext.Current.Request.Headers

Below is an Example.
public class MyController : Controller
{
[Route("~/api/mycontroller")]
[HttpGet]
public int ID()
{
try
{
return somecontroller.getID(ID);
}
catch (Exception ex)
{
throw ex;
}
}
}
Above it the controller that is fetching the ID from the below controller.
Below is the controller that it is inherited.
public class Controller : ApiController
{
public int ID
{
get
{
return int.Parse(HttpContext.Current.Request.Headers["ID"]);
}
}
}
How do i write unit test case for the following.???
Oh, unit testing HttpContext.Current. That's one of my favorites :-)
You can't write a unit test for something that depends on HttpContext.Current. So if you want to write testable code the first step is to search in your entire solution for the HttpContext.Current keyword and simply wipe them out from existence.
In this particular case you would of course replace them with the corresponding abstraction:
public class Controller : ApiController
{
public int ID
{
get
{
return int.Parse(Request.Headers.GetValues("ID").FirstOrDefault());
}
}
}
Now it's completely trivial to unit test your Web API controller properly:
// arrange
var sut = new MyController();
sut.Request = new HttpRequestMessage();
sut.Request.Headers.TryAddWithoutValidation("ID", "5");
// act
var actual = sut.SomeControllerAction();
// assert
Assert.AreEqual(5, actual);

VS 2010, Coded UI Tests: Re-run failed test cases

I'm using VS2010 Premium, Coded UI Tests.
Do you know how to re-execute failed test cases after run?
If test was passed after re-execution then it should be passed in result report.
Not so optimal way but you could put all your code to try/catch block and rerun the test if an exception is thrown:
[CodedUITest]
public class CodedUITest
{
private static int _maxTestRuns = 5;
[TestCleanup]
public void Cleanup()
{
//If the test has reached the max number of executions then it is failed.
if (_maxTestRuns == 0)
Assert.Fail("Test executed {0} times and it was failed", _maxTestRuns);
}
[TestMethod]
public void CodedUITestMethod()
{
try
{
this.UIMap.RecordedMethod1();
}
catch (Exception exception)
{
//Call Cleanup, rerun the test and report the error.
if (_maxTestRuns > 0)
{
_maxTestRuns--;
TestContext.WriteLine(exception.Message);
TestContext.WriteLine("Running Again...");
this.Cleaup();
this.CodedUITestMethod();
}
}
}
}
You could also generalize the method Schaliasos proposes, we could create a base class like this:
[CodedUITest]
public class _TestBase
{
private static int _maxTestRuns;
public Exception _currentException;
public _TestBase()
{
}
public void TryThreeTimes(Action testActions)
{
_maxTestRuns = 3;
_currentException = null;
while (_maxTestRuns > 0)
{
try
{
testActions();
}
catch (Exception exception)
{
_maxTestRuns--;
_currentException = exception;
}
if (_currentException == null)
break; // Test passed, stop retrying
}
if (_maxTestRuns == 0) // If test failed three times, bubble up the exception.
{
throw _currentException;
}
}
/// <summary>
///Gets or sets the test context which provides
///information about and functionality for the current test run.
///</summary>
public TestContext context
{
get
{
return testContextInstance;
}
set
{
testContextInstance = value;
}
}
private TestContext testContextInstance;
}
And then when we write tests we could inherit the class above and do this:
[CodedUITest]
public class NewTestClass : _TestBase
{
[TestMethod]
public void MyTestMethod1()
{
TryThreeTimes(new Action(() =>
// Assertions and Records come here
Assert.IsTrue(false);
}));
}
[TestMethod]
public void MyTestMethod2()
{
TryThreeTimes(new Action(() =>
// Assertions and Records come here.
Assert.IsTrue(true);
}));
}
}
I have been thinking about how this could be made even simpler, any suggestions would be appreciated. This at least saves quite a bit of code if you have many tests that you would like to run often, maybe it would make sense for some to generalize the function TryThreeTimes so one of the arguments would be the number of reruns.

How to pass a mvc-mini-profiler connection to a base class from MVC3

Given this snippet of code
public abstract class Foo
{
private static SqlConnection _sqlConnection;
protected SqlConnection GetOpenConnection()
{
if (_sqlConnection == null)
{
_sqlConnection = new SqlConnection("connection string");
}
return _sqlConnection;
}
protected abstract void Execute();
}
public class FooImpl : Foo
{
protected override void Execute()
{
var myConn = GetOpenConnection();
var dog = myConn.Query<dynamic>("select 'dog' Animal");
var first = dog.First();
string animalType = first.Animal;
// more stuff here
}
}
How would you wrap the connection in a profiled connection if you don't have access to the connection creation process? Rewrite the code in the super class and wrap it there? This would involve changing hundreds of classes that inherit from the base. I'd prefer a way to change the base class, with as little changes necessary to the supers.
Thank you,
Stephen
Well after a bit of trial and error I compromised and added a ref to MvcMiniProfiler in the base library and changed the connection code a bit.
protected DbConnection GetOpenConnection()
{
if (_connection == null)
{
_connection = new SqlConnection(ConfigurationManager.ConnectionStrings["connection string "].ConnectionString);
_connection.Open();
}
return MvcMiniProfiler.Data.ProfiledDbConnection.Get(_connection, MiniProfiler.Current);
}
private static SqlConnection _connection;
This works for both hosting in the MVC project (for profiling purposes, where we don't have that capability (QA/Prod Databases)) and WPF/Windows Service

How can I add a datasource to a UIMap method instead of a Test Method (VS 2010 Coded UI Test)

I have a 2010 Coded UI Test that performs some actions against a website. I am able to add a datasource to a "Test Method" which loops the entire method once per record.
But, what I really want to do is loop only a portion of the test which is just a single recorded method in the UIMap.
Let's say the test method looks something like this:
//[DataSource("Microsoft.VisualStudio.TestTools.DataSource.XML", "|DataDirectory|\\TestCommunities.xml", "Community", DataAccessMethod.Sequential), DeploymentItem("Tests\\WebTests\\DataSources\\TestCommunities.xml"), TestMethod]
public void LoginCreateCommunities()
{
this.UIMap.LoginAdmin();
//this.UIMap.CreateCommunityParams.UIItem0EditText = TestContext.DataRow["CommunityName"].ToString();
this.UIMap.CreateCommunity();
this.UIMap.LogoffClose();
}
It's only UIMap.CreateCommunity() that I want to loop the datasource. I do not want all 3 methods to execute per record in the datasource, which is what happens when I attach the datasource to the test method (the portion commented out above).
Is there a way to achieve what I'm trying to do here?
Thanks.
You have to use the ClassInitialize and ClassCleanup methods. You place it in the #region Additional test attributes area at the bottom. So for you it'd look something like:
#region Additional test attributes
[ClassInitialize]
static public void ClassInit(TestContext context)
{
Playback.Initialize();
try
{
sharedTest.LoginAdmin();
}
finally
{
Playback.Cleanup();
}
}
[ClassCleanup]
static public void ClassCleanup()
{
Playback.Initialize();
try
{
sharedTest.LogoffClose();
}
finally
{
Playback.Cleanup();
}
}
#endregion
first you have to define a new UIMap in your codedUI class
[CodedUITest]
public class CodedUITest1
{
static private UIMap sharedTest = new UIMap();
....
[ClassInitialize()]
static public void ClassInit(TestContext context)
{
Playback.Initialize();
try
{
sharedTest.RecordedStartApp();
}
finally
{
Playback.Cleanup();
}
}
[ClassCleanup()]
static public void ClassCleanup()
{
Playback.Initialize();
try
{
sharedTest.RecordedCloseApp();
}
finally
{
Playback.Cleanup();
}
}
}

Resources