I'm trying to validate that SetFirefoxOptions() is called when I call GetFirefoxDriver(). But for whatever reason, Moq keeps telling me that it wasn't called. What am I doing wrong?
Here's my test:
[TestMethod]
public void ShouldSetFirefoxOptions()
{
var stubCapabilities = new Mock<SauceCaps>().Object;
var mockManager = new Mock<DriverManager>();
mockManager.Setup(
m => m.GetFirefoxDriver(stubCapabilities)).
Returns(It.IsAny<IWebDriver>());
mockManager.Verify(
m => m.SetFirefoxOptions(stubCapabilities));
}
DriverManager.cs:
public class DriverManager : IDriverManager
{
public virtual Dictionary<string, object> SauceOptions { get; private set; }
public DriverManager()
{
}
public virtual IWebDriver GetFirefoxDriver(SauceCaps sauceCaps)
{
var browserOptions = SetFirefoxOptions(sauceCaps);
return new RemoteWebDriver(new Uri("https://ondemand.saucelabs.com/wd/hub"),
browserOptions.ToCapabilities(), TimeSpan.FromSeconds(600));
}
public virtual FirefoxOptions SetFirefoxOptions(SauceCaps sauceCaps)
{
return new FirefoxOptions
{
BrowserVersion = sauceCaps.BrowserVersion,
PlatformName = sauceCaps.Os
};
}
}
The problem with your code is that it is unclear what is your System Under Test. You are mocking and testing the same class at the same time. Although it is technicaly possible using moq (using CallBase) it is in principle wrong approach.
The one possibility is to extract SetFirefoxOptions into separate interface and inject it into the DriverManager, e.g.
public interface IFirefoxOptionCreator
{
FirefoxOptions SetFirefoxOptions(SauceCaps sauceCaps);
}
public DeviceManager(IFirefoxOptionCreator optionCreator)
{
_optionCreator = optionCreator;
}
public virtual IWebDriver GetFirefoxDriver(SauceCaps sauceCaps)
{
var browserOptions = _optionCreator.SetFirefoxOptions(sauceCaps);
return new RemoteWebDriver(new Uri("https://ondemand.saucelabs.com/wd/hub"),
browserOptions.ToCapabilities(), TimeSpan.FromSeconds(600));
}
then you could easily verify is interface method was called within your unit tests:
[TestMethod]
public void ShouldSetFirefoxOptions()
{
// Arrange
var stubCapabilities = new Mock<SauceCaps>().Object;
var optionCreatorMock = new Mock<IFirefoxOptionCreator>();
optionCreatorMock.Setup(m => m.SetFirefoxOptions(It.IsAny<SauceCaps>()))
.Returns(new FirefoxOptions());
var sut = new DriverManager();
// Act
_ = sut.GetFirefoxDriver(stubCapabilities);
// Assert
optionCreatorMock.Verify(m => m.SetFirefoxOptions(stubCapabilities));
}
Related
AutoFixture will not work with register and additional customize call. If I do only one of the two, it works. The whole behavior of customize feature is hard to understand for me. Is this works as designed?
Goal: Use the greediest constructor AND OmitAutoProperties for special class.
public interface IDataProvider { }
public class FileDataProvider : IDataProvider {}
public class TestClass
{
public TestClass() : this (new FileDataProvider()) { }
public TestClass(IDataProvider dataProvider) { } // should be used from AutoFixture
}
[Fact]
public void Method_State_Result()
{
var fixture = new Fixture();
fixture.Register(() => fixture.Build<TestClass>().OmitAutoProperties().Create());
var dc1 = fixture.Create<TestClass>(); // working
fixture.Customize(new AutoNSubstituteCustomization());
fixture.Customizations.Add(new MethodInvoker(new GreedyConstructorQuery()));
var dc2 = fixture.Create<TestClass>(); // crash with "AutoFixture was unable to create an instance from System.SByte*, most likely because it has no public constructor, is an abstract or non-public type"
var dc3 = fixture.Create<TestClass>();
}
A workaround would be to do the registration like this. But feels not like the right solution...
fixture.Register(() => new Fixture().Build<TestClass>().OmitAutoProperties().Create());
If I understood the question correctly, then the easiest option is to provide a custom factory that uses a specimen builder.
fixture.Customize<TestClass>(c => c
.FromFactory(new MethodInvoker(new GreedyConstructorQuery()))
.OmitAutoProperties());
Here is a sample test.
public class TestClass
{
public TestClass() : this(new FileDataProvider())
{
}
public TestClass(IDataProvider dataProvider)
{
DataProvider = dataProvider;
}
public string SomeString { get; set; }
public IDataProvider DataProvider { get; }
}
[Fact]
public void FooTest()
{
var fixture = new Fixture().Customize(new AutoMoqCustomization());
fixture.Customize<TestClass>(c => c
.FromFactory(new MethodInvoker(new GreedyConstructorQuery()))
.OmitAutoProperties());
var mockProvider = fixture.Freeze<IDataProvider>();
var testObject = fixture.Create<TestClass>();
Assert.Null(testObject.SomeString);
Assert.Same(mockProvider, testObject.DataProvider);
}
I have a custom implementation of CodeAccessSecurityAttribute that is connecting external sources to do a validation.
[Serializable]
[AttributeUsage(AttributeTargets.Method)]
public class IsAuthorizedAttribute : CodeAccessSecurityAttribute
{
private static readonly PrincipalPermission Allowed = new PrincipalPermission(PermissionState.None);
private static readonly PrincipalPermission NotAllowed = new PrincipalPermission(PermissionState.Unrestricted);
public string EntityObject { get; set; }
public string Field { get; set; }
public char Expected { get; set; }
public IsAuthorizedAttribute(SecurityAction action)
: base(action)
{
//setup
}
public override IPermission CreatePermission()
{
return IsAuthorised(EntityObject, Field, Expected, ServicesConfiguration) ? Allowed : NotAllowed;
}
private static bool IsAuthorised(string entityObject, string field, char expected, ServicesConfiguration servicesConfiguration)
{
bool? response = null;
//check external stuff
return response ?? false;
}
}
I have decorated my methods with this attribute:
[IsAuthorized(SecurityAction.Demand, EntityObject = Fields.UserManagement, Field = Fields.AllowDisplay, Expected = '1')]
public List<Group> GetUserGroups()
{
var response = new List<Group>();
//Get the groups from the database
var groups = groupManager.FindAll();
//Map them to the output group type
response = groups.Select(x => new Group()
{
ID = x.ID,
Name = x.Name,
Alias = x.Alias,
Description = x.Description
}).ToList();
return response;
}
I now want to unit test this method, but the attribute is fired. I have tried some things to mock the attribute, but without success.
I'm using Moq and Smocks.
This is my unit test without a mocked instance of the attribute:
[TestMethod]
public void GetUserGroups_UserGroupsFound_UserGroupsReturned()
{
Smock.Run(context =>
{
//Arrange
Setup();
m_Container
.RegisterMock<IGroupManager>()
.Setup(x => x.FindAllFromCache())
.Returns(new List<Concept.Security.MasterData.Domain.Group>()
{
new Concept.Security.MasterData.Domain.Group()
{
Name = "MyUserGroup",
Alias = "My User Group",
Description = "My user group description",
System = false,
Authorizations = "000001111100000000"
},
new Concept.Security.MasterData.Domain.Group()
{
Name = "MySecondUserGroup",
Alias = "My Second User Group",
Description = "My second user group description",
System = false,
Authorizations = "000000000000000000"
}
});
var identityService = new UserManagementService(m_Container, m_UserAuthorizationManager.Object, m_IdentityService.Object);
//** begin add mocked attribute **//
//** end add mocked attribute **//
//Act
var response = identityService.GetUserGroups();
//Assert
Assert.AreEqual(2, response.Count);
Assert.AreEqual(1, response.Where(x => x.Alias == "MyUserGroup").Count());
Assert.AreEqual(1, response.Where(x => x.Alias == "MySecondUserGroup").Count());
Assert.AreEqual(2, response.Where(x => x.Authorizations == null).Count());
});
}
Running this results in an exception because the attribute tries to connect the external services and they aren't (and can't be) setup to receive requests.
So, I try to add a mocked attribute:
//** begin add mocked attribute **//
var identityService = new UserManagementService(m_Container, m_UserAuthorizationManager.Object, m_IdentityService.Object);
var IsAuthorizedAttribute = new Mock<IsAuthorizedAttribute>(MockBehavior.Strict, new object[] { SecurityAction.Demand });
IsAuthorizedAttribute.Setup(x => x.CreatePermission()).Returns(new PrincipalPermission(PermissionState.None));
TypeDescriptor.AddAttributes(identityService, IsAuthorizedAttribute.Object);
//** end add mocked attribute **//
But this one is calling the constructor of the attribute where I set up the external source. When I put this constructor in a try/catch and silently disposing the exception, I have an error on IsAuthorizedAttribute.Object object can't be found.
What are other options to not fire the attribute?
Constructors should not access externals; otherwise it will be difficult to bypass for testing, as you know.
A simple way is to make static bool field to bypass. This does not look so good but maybe enough.
public class IsAuthorizedAttribute : CodeAccessSecurityAttribute
{
// set true in the test initialization
private static bool s_byPass;
public IsAuthorizedAttribute(SecurityAction action) : base(action)
{
if (!s_byPass)
{
// setup
}
}
private static bool IsAuthorised(string entityObject, string field, char expected, ServicesConfiguration servicesConfiguration)
{
if (s_byPass) { return true; }
//check external stuff
}
}
Another better approach is to extract the external dependency to another class so that you can mock it. Mocking external dependencies is a typical pattern of a unit test.
public class IsAuthorizedAttribute : CodeAccessSecurityAttribute
{
// set mock here in the test initialization.
// I assume external accessor can be a static field.
private static ExternalAccessor m_accessor = new ExternalAccessor();
private static bool IsAuthorised(string entityObject, string field, char expected, ServicesConfiguration servicesConfiguration)
{
return m_accessor.Check();
}
}
public class ExternalAccessor
{
private bool m_initialized;
private void Setup()
{
// setup
m_initialized = true;
}
public virtual bool Check()
{
// You can call setup anytime but the constructor.
if (!m_initialized) { Setup(); }
// check external stuff
}
}
I've got a setup like this with a concrete class that is instantiated inside the method I want to test. I want to mock this concrete class an not have it execute the code inside. Hence, no exception should be thrown:
public class Executor
{
public bool ExecuteAction(ActionRequest request)
{
switch (request.ActionType)
{
case ActionType.Foo:
var a = new Foo();
return a.Execute(request);
case ActionType.Bar:
var b = new Bar();
return b.Execute(request);
}
return true;
}
}
public class Foo
{
public virtual bool Execute(ActionRequest request)
{
throw new NotImplementedException();
}
}
public class Bar
{
public virtual bool Execute(ActionRequest request)
{
throw new NotImplementedException();
}
}
My NUnit test looks like this:
[Test]
public void GivenARequestToFooShouldExecuteFoo()
{
var action = new Mock<Foo>();
action.Setup(x => x.Execute(It.IsAny<ActionRequest>())).Returns(true);
var sut = new Mock<Executor>();
sut.Object.ExecuteAction(new ActionRequest
{
ActionType = ActionType.Foo
});
}
[Test]
public void GivenARequestToBarShouldExecuteBar()
{
var action = new Mock<Bar>();
action.Setup(x => x.Execute(It.IsAny<ActionRequest>())).Returns(true);
var sut = new Mock<Executor>();
sut.Object.ExecuteAction(new ActionRequest
{
ActionType = ActionType.Bar
});
}
I fiddled around with CallBase, but it didn't get me anywhere. Is there anyway I can solve this easily without dependency injection of these classes and adding interfaces? Is this possible just using Moq?
The only thing I can think to do currently is move the Execute methods into the Executor class and rename them to ExecuteFoo() and ExecuteBar(), but I have a lot of code to move so they'd have to be partial classes (sub classes?).
The problem is not with the mocking of the method but with the creation of the concrete class. The creation of Foo and Bar need to be inverted out of the Executor. It is responsible for executing the action, not creating it. with that this interface was created to handle the creation.
public interface IActionCollection : IDictionary<ActionType, Func<IExecute>> {
}
think of this as a collection of factories or a collection of creation strategies.
A common interface was created for the actions.
public interface IExecute {
bool Execute(ActionRequest request);
}
public class Foo : IExecute {
public virtual bool Execute(ActionRequest request) {
throw new NotImplementedException();
}
}
public class Bar : IExecute {
public virtual bool Execute(ActionRequest request) {
throw new NotImplementedException();
}
}
And the Executor was refactored to use dependency inversion.
public class Executor {
readonly IActionCollection factories;
public Executor(IActionCollection factories) {
this.factories = factories;
}
public bool ExecuteAction(ActionRequest request) {
if (factories.ContainsKey(request.ActionType)) {
var action = factories[request.ActionType]();
return action.Execute(request);
}
return false;
}
}
With that refactor done the Executor can be tested with fake actions.
public void GivenARequestToFooShouldExecuteFoo() {
//Arrange
var expected = true;
var key = ActionType.Foo;
var action = new Mock<Foo>();
action.Setup(x => x.Execute(It.IsAny<ActionRequest>())).Returns(expected);
var actions = new Mock<IActionCollection>();
actions.Setup(_ => _[key]).Returns(() => { return () => action.Object; });
actions.Setup(_ => _.ContainsKey(key)).Returns(true);
var sut = new Executor(actions.Object);
var request = new ActionRequest {
ActionType = ActionType.Foo
};
//Act
var actual = sut.ExecuteAction(request);
//Assert
Assert.AreEqual(expected, actual);
}
A production implementation of the factory collection can look like this
public class ActionCollection : Dictionary<ActionType, Func<IExecute>>, IActionCollection {
public ActionCollection()
: base() {
}
}
and configured accordingly with your concrete types.
var factories = ActionCollection();
factories[ActionType.Foo] = () => new Foo();
factories[ActionType.Bar] = () => new Bar();
I am testing my class
public class myclass
{
private IAwesome awesomeObject;
public myclass(IAwesome awesomeObject)
{
this.awesomeObject = awesomeObject;
}
public void MethodUnderTest()
{
this.awesomeObject.RunSomething(); //I want to verify that RunSomething was called
}
}
The way I am doing this is:
//Arrange
var mockAwesome = new Mock<IAwesome>();
mockAwesome.Setup(x=>x.RunSomething()).Returns ... Verify()...;
//Act
var sut = new myclass(mockAwesome.object);
sut.MethodUnderTest();
//Assert
mockAwesome.Verify();
The exception I am getting is:
System.NotSupportedException : Expression references a method that
does not belong to the mocked object: x => x.RunSomething
Is it not possible to test that a specific method was executed on a mocked object that I passed into a class, that is now part of a private member of that class?
Modify set up line to mockAwesome.Setup(x=>x.RunSomething()).Verifiable() and it should work for the example you provided.
[TestClass]
public class MoqVerificationTest {
[TestMethod]
public void Moq_Should_Verify_Setup() {
//Arrange
var mockAwesome = new Mock<IAwesome>();
mockAwesome.Setup(x => x.RunSomething()).Verifiable();
//Act
var sut = new myclass(mockAwesome.Object);
sut.MethodUnderTest();
//Assert
mockAwesome.Verify();
}
public interface IAwesome {
void RunSomething();
}
public class myclass {
private IAwesome awesomeObject;
public myclass(IAwesome awesomeObject) {
this.awesomeObject = awesomeObject;
}
public void MethodUnderTest() {
this.awesomeObject.RunSomething(); //I want to verify that RunSomething was called
}
}
}
To confirm, comment out this.awesomeObject.RunSomething() in your sample class and run the test again. It will fail because you setup the RunSomething as Verifiable() and it was not used.
When testing, works perfectly fine for me...
Try this approach see if anything different results...
void Main()
{
IAwesome awesome = Mock.Of<IAwesome>();
Mock<IAwesome> mock = Mock.Get(awesome);
mock.Setup(m => m.RunSomething());
MyClass myClass = new MyClass(awesome);
myClass.MethodUnderTest();
mock.Verify(m => m.RunSomething(), Times.Once);
}
public interface IAwesome
{
void RunSomething();
}
public class MyClass
{
private IAwesome awesomeObject;
public myclass(IAwesome awesomeObject)
{
this.awesomeObject = awesomeObject;
}
public void MethodUnderTest()
{
this.awesomeObject.RunSomething();
}
}
This is my Domain class
public partial class Department
{
public int DepartmentId { get; set; }
[Required]
public string DepartmentCode { get; set; }
[Required]
public string DepartmentFullName { get; set; }
public bool Status { get; set; }
public System.DateTime CreatedOn { get; set; }
}
In my MVC application, this is how my DepartmentService class looks like.
public class DepartmentService : IDepartmentService
{
private IUnitOfWork _UoW;
private IRepository<Department> repository;
public DepartmentService(IUnitOfWork UoW)
{
_UoW = UoW;
repository = _UoW.GetRepository<Department>();
}
public IList<Department> GetAllDepartments()
{
return repository.GetAll();
}
public bool SaveDepartment(Department newDepartment)
{
try
{
repository.Add(newDepartment);
_UoW.Save();
}
catch (Exception)
{
throw;
}
return true;
}
}
I wrote one unit test for GetAllDepartments methods as below.
[Test]
public void When_GetAllDepartments_Is_Called_RepositoryGetAll_ShouldBeCalled()
{
// Arrange
var mockUnitOfWork = new Mock<IUnitOfWork>();
var mockRepository = new Mock<IRepository<Department>>();
mockUnitOfWork.Setup(x => x.GetRepository<Department>())
.Returns(mockRepository.Object);
var sut = new DepartmentService(mockUnitOfWork.Object);
// Act
sut.GetAllDepartments();
// Assert
mockRepository.Verify(x => x.GetAll());
}
I want to test the SaveDepartment method where, when department is saved successfully, it should return true. I am not able to write unit test for this.
I also want to test when DepartmentCode or DepartmentFullName is blank and if Save is attempted, an exception should be thrown.
This is what i have so far.
[Test]
public void ShouldSucessfully_SaveNewDepartment()
{
// Arrange
var mockUnitOfWork = new Mock<IUnitOfWork>();
var mockRepository = new Mock<IRepository<Department>>();
Department newDept = new Department {
CreatedOn = DateTime.Now,
Status = true,
DepartmentFullName = "DFN",
DepartmentCode = "DC" };
mockUnitOfWork.Setup(x => x.GetRepository<Department>())
.Returns(mockRepository.Object);
var sut = new DepartmentService(mockUnitOfWork.Object);
// Act
sut.SaveDepartment(newDept);
// Assert
// ???
}
First of all - move all common arrange code to SetUp method:
private Mock<IUnitOfWork> mockUnitOfWork;
private Mock<IRepository<Department>> mockRepository;
private DepartmentService sut;
[SetUp]
public void SetUp()
{
mockUnitOfWork = new Mock<IUnitOfWork>();
mockRepository = new Mock<IRepository<Department>>();
mockUnitOfWork.Setup(x => x.GetRepository<Department>())
.Returns(mockRepository.Object);
sut = new DepartmentService(mockUnitOfWork.Object);
}
// tests will be here
That will make tests much easier to read and maintain. Next - do not stick to implementation when naming your tests:
When_GetAllDepartments_Is_Called_RepositoryGetAll_ShouldBeCalled
What if you will rename repository method to FindAll? What if service method will be renamed? Test becomes obsolete. And nobody will know about that. You should describe WHAT your SUT should do instead of HOW:
[Test]
public void ShouldGetAllDepartments()
{
var expected = new List<Department>{ CreateDepartment(), CreateDepartment()};
mockRepository.Setup(r => r.GetAll()).Returns(expected);
var actual = sut.GetAllDepartments();
Assert.That(actual, Is.EqualTo(expected));
mockRepository.VerifyAll();
}
As you can see, test name changed. Also I verify different things here - not only repository was called (that check can be removed actually), but that service returns exactly same departments which it gets from repository. Thats what service does. And second test:
[Test]
public void ShouldSucessfullySaveNewDepartment()
{
var department = CreateDepartment();
mockRepository.Setup(r => r.Add(department));
var result = sut.SaveDepartment(department);
Assert.True(result);
mockRepository.VerifyAll();
mockUnitOfWork.Verify(u => u.Save());
}
It verifies following service behavior: service should pass to repository exactly same department instance which was passed to service, and it should return true, it also calls save on unit of work to submit data.
BTW As you can see above I use helper method to make tests more clean:
private Department CreateDepartment()
{
return new Department {
CreatedOn = DateTime.Now,
Status = true,
DepartmentFullName = "DFN",
DepartmentCode = "DC"
};
}
And bonus - verifying that service does not saves department which already exists:
[Test]
public void ShouldNotSaveExistingDepartment()
{
mockUnitOfWork.Setup(u => u.Save()).Throws<NonUniqueEntityException>();
var result = sut.SaveDepartment(CreateDepartment());
Assert.False(result);
mockUnitOfWork.VerifyAll();
}
As you can see, expected behavior is simple - when unit of work throws NonUniqueEntityException during department saving, service should return false. Yes, I think it's better to return false. Here is service code which makes this test pass:
public bool SaveDepartment(Department department)
{
try
{
repository.Add(department);
_UoW.Save();
return true;
}
catch (NonUniqueEntityException e)
{
// log exception
return false;
}
}
First of all remove the redundant try...catch.
There's no point in catching an exception just to rethrow it.
As far as the test you asked for here is the snippet:
[Test]
public void ShouldSucessfully_SaveNewDepartment()
{
// Arrange
var mockUnitOfWork = new Mock<IUnitOfWork>();
var mockRepository = new Mock<IRepository<Department>>();
Department newDept = new Department { CreatedOn = DateTime.Now, Status = true, DepartmentFullName = "DFN", DepartmentCode = "DC" };
mockUnitOfWork.Setup(x => x.GetRepository<Department>()).Returns(mockRepository.Object);
var sut = new DepartmentService(mockUnitOfWork.Object);
// Act
bool result = sut.SaveDepartment(newDept);
// Assert
Assert.That(result, Is.True);
}
[Test]
public void ShouldThrowExceptionWhenExceptionThrownInternally_SaveNewDepartment()
{
// Arrange
var mockUnitOfWork = new Mock<IUnitOfWork>();
var mockRepository = new Mock<IRepository<Department>>();
mockUnitOfWork.Setup(x => x.GetRepository<Department>()).Returns(mockRepository.Object);
mockUnitOfWork.Setup(uow => uow.Save()).Throws<Exception>();
var sut = new DepartmentService(mockUnitOfWork.Object);
// Act
TestDelegate action = () => sut.SaveDepartment(new Department());
// Assert
Assert.Throws<Exception>(action);
}
I also want to test when DepartmentCode or DepartmentFullName is blank and if Save is attempted, an exception should be thrown.
It depend on who you expect to check for those values: if you want to rely on you database or unitofwork to check for those fields this is not the fixture to test for specific failure conditions it you want a unit test. Here you should only test what happens in case uow throws exception.
If you plan to add those check in the department service than you can do the following:
[Test]
public void ShouldThrowExceptionWhenDepartmentCodeIsNull_SaveNewDepartment()
{
// Arrange
var mockUnitOfWork = new Mock<IUnitOfWork>();
Department newDept = new Department
{
CreatedOn = DateTime.Now,
Status = true, DepartmentFullName = "DFN",
DepartmentCode = null
};
var sut = new DepartmentService(mockUnitOfWork.Object);
// Act
TestDelegate action = () => sut.SaveDepartment(newDept);
// Assert
Assert.Throws<ArgumentException>(action);
}
provided that you modified your method as follows:
public bool SaveDepartment(Department newDepartment)
{
if (string.IsNullOrEmpty(newDepartment.DepartmentCode))
{
throw new ArgumentException("DepartmentCode must be not null");
}
repository.Add(newDepartment);
_UoW.Save();
return true;
}