Limiting Scope of UnitTest using Rhino stubs - c#

I'm working on a unit test for a service method, that has dependencies. Simplified:
public class ConditionChecker
{
private SqlConnection _connection;
public bool CanDoSomething()
{
return _connection.State == ConnectionState.Open;
}
}
public class A
{
public ConditionChecker Checker { get; set; }
public bool CanInvokeA()
{
return Checker.CanDoSomething();
}
}
[TestClass]
public class ATests
{
[TestMethod]
public void TestCanInvokeA()
{
// arrange
A a = new A();
ConditionChecker checker = MockRepository.GenerateStub<ConditionChecker>();
checker.Stub(x => x.CanDoSomething()).Return(true);
a.Checker = checker;
// act
bool actual = a.CanInvokeA();
// assert
Assert.AreEqual(true, actual);
}
}
What I want is to completely bypass the implementation of ConditionChecker.CanDoSomething, which is why I stub the call, still I run into a null reference Exception during my test, since the _connection member is not set. What am I doing wrong here?

You just mark your method as virtual, it will work:
public virtual bool CanDoSomething()
{
}
Since behind the scene Rhino Mock will create a dynamic proxy for ConditionChecker, so you need to mark virtual to allow Rhino Mock to override it.

Related

Mocking an object initialised inside a method under test

I am trying to test a class which instatiates another class within it. It is the instatinated class call I want to mock.
Is this possible or is they a way around it/ simpler way I am missing?
Below I have written up a simpler example which still has the same problemts as my main code.
public interface my_interface
{
int returns_25();
}
public class class_i_want_to_mock : my_interface
{
public int returns_25()
{
// TEST SHOULD FAIL SO NEED MOCK TO PASS THE CASE
return 7645745;
}
}
In another namespace (it has access):
public class class_to_test
{
public static int returns_25()
{
class_i_want_to_mock _tempClass= new class_i_want_to_mock ();
// Will return 7645745 unless moq changes return value
int _temp_int = _tempClass.returns_25()
return _temp_int;
}
}
My test (which fails):
[Test]
public void test_returns_25()
{
// Mock
Mock<my_interface> myMock = new Mock<my_interface>();
myMock.Setup(m => m.returns_25()).Returns(25);
// Act
int return_number = class_to_test.returns_25();
// Assert
Assert.AreEqual(25, return_number);
}
Here is working code thanks to the injection idea from JSteward above.
Code is in same order
public interface my_interface
{
int returns_25();
}
public class class_i_want_to_mock : my_interface
{
public int returns_25()
{
// TEST SHOULD FAIL SO NEED MOCK TO PASS THE CASE
return 7645745;
}
}
Next class, notice the injection of the interface
public class class_to_test
{
public static int returns_25(my_interface _temp_interface)
{
// Will return 7645745 unless moq changes return value
int _temp_int = _temp_interface.returns_25()
return _temp_int;
}
}
And the test. Note the object of the Mock class has to be used (myMock.Object)
[Test]
public void test_returns_25()
{
// Mock
Mock<my_interface> myMock = new Mock<my_interface>();
myMock.Setup(m => m.returns_25()).Returns(25);
// Act
int return_number = class_to_test.returns_25(myMock.Object);
// Assert
Assert.AreEqual(25, return_number);
}

How to skip a Unit Test at runtime?

Thanks in advance!
We have some Automation tests using the selenium web driver which are great and provide a really good regression pack.
The problem is now we have feature toggles in our code. So I need to say ignore these tests unless that feature toggle is turned On/ Off. I can't find anything really searching Google.
Ideally I don't want a 'if' statement at the top of the Feature tests but it looks like it's going to be the main way. My initial thoughts where to create a custom attribute
public class IsFeatureFlagTurnedOn : Attribute
{
public IsFeatureFlagTurnedOn(string featureToggleName)
{
FeatureToggleName = featureToggleName;
}
public string FeatureToggleName {get;}
}
public class MyTests
{
[TestMethod]
[IsFeatureFlagTurnedOn("MyFeature1")]
public void ItShould()
{
// only run if MyFeature1 is turned on
}
}
I some how need to hook into the MSTest pipeline and say if this attribute is present and the logic for MyFeature1 is turned off then don't run this test - Looked at dynamically adding the [Ignore] but with no luck.
This is running through VSTS and I could use [TestCategories] but I'd have to keep updating the pipeline to which feature is turned on/off which I don't want to do.
Any help or suggestions would be great!
MSTest v2 now has a lot of extensibility points, and you can achieve this by extending the TestMethodAttribute. First we add two attribute arguments, a string for a property name and a Type that has the property. Then we override the Execute method and invoke the property via reflection. If the result is true, we'll execute the test as normal, otherwise we return an 'inconclusive` test result.
public class TestMethodWithConditionAttribute : TestMethodAttribute
{
public Type ConditionParentType { get; set; }
public string ConditionPropertyName { get; set; }
public TestMethodWithConditionAttribute(string conditionPropertyName, Type conditionParentType)
{
ConditionPropertyName = conditionPropertyName;
ConditionParentType = conditionParentType;
}
public override TestResult[] Execute(ITestMethod testMethod)
{
if (ConditionParentType.GetProperty(ConditionPropertyName, BindingFlags.Static | BindingFlags.Public)?.GetValue(null) is bool condiiton && condiiton)
{
return base.Execute(testMethod);
}
else
{
return new TestResult[] { new TestResult { Outcome = UnitTestOutcome.Inconclusive } };
}
}
}
Now we can use our new attribute like this:
[TestClass]
public class MyTests
{
[TestMethodWithCondition(nameof(Configuration.IsMyFeature1Enabled), typeof(Configuration))]
public void MyTest()
{
//...
}
}
public static class Configuration
{
public static bool IsMyFeature1Enabled => false;
}
The above is a very generic solution. You could also customize it a little more to your particular use case to perhaps avoid quite so much verbosity in the attribute declaration:
public class TestMethodForConfigAttribute : TestMethodAttribute
{
public string Name { get; set; }
public TestMethodForConfigAttribute(string name)
{
Name = name;
}
public override TestResult[] Execute(ITestMethod testMethod)
{
if (IsConfigEnabled(Name))
{
return base.Execute(testMethod);
}
else
{
return new TestResult[] { new TestResult { Outcome = UnitTestOutcome.Inconclusive } };
}
}
public static bool IsConfigEnabled(string name)
{
//...
return false;
}
}
And use it like:
[TestClass]
public class MyTests
{
[TestMethodForConfig("MyFeature1")]
public void MyTest()
{
//...
}
}
Based on my reading of this, you may need to use Assert.Inconclusive

Moq - Verify no methods were called except one

I have a controller with a method that reads configuration to determine which other method(s) to call. Depending on the config, it may call zero, one, or all of the WorkerMethodN() methods.
public class MyController
{
public virtual bool EntranceMethod()
{
// read configuration to determine which methods to call
}
public virtual void WorkerMethod1() { ... }
public virtual void WorkerMethod2() { ... }
public virtual void WorkerMethod3() { ... }
}
I am trying to test this EntranceMethod() and my first test is to determine behavior when the configuration is empty. When the configuration returns nothing, I want to ensure that none of the WorkerMethodN() methods are called.
My test so far:
[TestMethod]
public void ShouldNotCallAnyMethodsWhenConfigurationReturnsNull()
{
this.mockConfigurationReader
.Setup(cr => cr.GetEnabledConfigurations())
.Returns((IEnumerable<Configuration>)null);
Mock<MyController> mockController =
new Mock<MyController>(MockBehavior.Strict, this.mockConfigurationReader.Object);
mockController.Object.EntranceMethod();
// todo: verify no additional methods are called
}
This call fails with the Exception: invocation failed with mock behavior Strict. All invocations on the mock must have a corresponding setup. when the call to EntranceMethod() is made.
How do I use MockBehavior.Strict and setup my controller to call EntranceMethod() and verify that no other methods are called? If I call .Setup() on my EntranceMethod(), it won't run the actual code I want it to. But if I don't call .Setup(), I get an exception.
For demonstrative purposes only, assume the following
public class Configuration {
}
public interface IConfigurationReader {
IEnumerable<Configuration> GetEnabledConfigurations();
}
public class MyController {
private IConfigurationReader configReader;
public MyController(IConfigurationReader configReader) {
this.configReader = configReader;
}
public virtual bool EntranceMethod() {
// read configuration to determine which methods to call
var config = configReader.GetEnabledConfigurations();
//...code for example purposes only
if (config != null) {
WorkerMethod1();
WorkerMethod2();
WorkerMethod3();
return true;
}
return false;
}
public virtual void WorkerMethod1() {
//...
}
public virtual void WorkerMethod2() {
//...
}
public virtual void WorkerMethod3() {
//...
}
}
Remove MockBehavior.Strict, enable CallBase = true then setup and check the other methods were not called using .Verify(......., Times.Never())
[TestClass]
public class MyControllerTest {
[TestMethod]
public void ShouldNotCallAnyMethodsWhenConfigurationReturnsNull() {
//Arrange
var mockConfigurationReader = new Mock<IConfigurationReader>();
mockConfigurationReader
.Setup(cr => cr.GetEnabledConfigurations())
.Returns((IEnumerable<Configuration>)null);
var mockController = new Mock<MyController>(mockConfigurationReader.Object) {
CallBase = true
};
//Act
mockController.Object.EntranceMethod();
//Assert
// todo: verify no additional methods are called
mockController.Verify(_ => _.WorkerMethod1(), Times.Never());
mockController.Verify(_ => _.WorkerMethod2(), Times.Never());
mockController.Verify(_ => _.WorkerMethod3(), Times.Never());
}
}
Reference Moq Quickstart
Modern answer (Moq 4.8 or later):
mock.Verify(...);
mock.VerifyNoOtherCalls();
That code does 2 things:
Verifies that any expected calls were made
Verifies that no other calls were made
Source: Moq Quickstart

Test Environment.Exit() in C#

Is there in C# some kind of equivalent of ExpectedSystemExit in Java? I have an exit in my code and would really like to be able to test it. The only thing I found in C# is a not really nice workaround.
Example Code
public void CheckRights()
{
if(!service.UserHasRights())
{
Environment.Exit(1);
}
}
Test Code
[TestMethod]
public void TestCheckRightsWithoutRights()
{
MyService service = ...
service.UserHasRights().Returns(false);
???
}
I am using the VS framework for testing (+ NSubstitute for mocking) but it is not a problem to switch to nunit or whatever for this test.
You should use dependency injection to supply to the class being tested an interface that provides an environmental exit.
For example:
public interface IEnvironment
{
void Exit(int code);
}
Let's also assume that you have an interface for calling UserHasRights():
public interface IRightsService
{
bool UserHasRights();
}
Now suppose your class to be tested looks like this:
public sealed class RightsChecker
{
readonly IRightsService service;
readonly IEnvironment environment;
public RightsChecker(IRightsService service, IEnvironment environment)
{
this.service = service;
this.environment = environment;
}
public void CheckRights()
{
if (!service.UserHasRights())
{
environment.Exit(1);
}
}
}
Now you can use a mocking framework to check that IEnvironment .Exit() is called under the right conditions. For example, using Moq it might look a bit like this:
[TestMethod]
public static void CheckRights_exits_program_when_user_has_no_rights()
{
var rightsService = new Mock<IRightsService>();
rightsService.Setup(foo => foo.UserHasRights()).Returns(false);
var enviromnent = new Mock<IEnvironment>();
var rightsChecker = new RightsChecker(rightsService.Object, enviromnent.Object);
rightsChecker.CheckRights();
enviromnent.Verify(foo => foo.Exit(1));
}
Ambient contexts and cross-cutting concerns
A method such as Environment.Exit() could be considered to be a cross-cutting concern, and you might well want to avoid passing around an interface for it because you can end up with an explosion of additional constructor parameters. (Note: The canonical example of a cross cutting concern is DateTime.Now.)
To address this issue, you can introduce an "Ambient context" - a pattern which allows you to use a static method while still retaining the ability to unit test calls to it. Of course, such things should be used sparingly and only for true cross-cutting concerns.
For example, you could introduce an ambient context for Environment like so:
public abstract class EnvironmentControl
{
public static EnvironmentControl Current
{
get
{
return _current;
}
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
_current = value;
}
}
public abstract void Exit(int value);
public static void ResetToDefault()
{
_current = DefaultEnvironmentControl.Instance;
}
static EnvironmentControl _current = DefaultEnvironmentControl.Instance;
}
public class DefaultEnvironmentControl : EnvironmentControl
{
public override void Exit(int value)
{
Environment.Exit(value);
}
public static DefaultEnvironmentControl Instance => _instance.Value;
static readonly Lazy<DefaultEnvironmentControl> _instance = new Lazy<DefaultEnvironmentControl>(() => new DefaultEnvironmentControl());
}
Normal code just calls EnvironmentControl.Current.Exit(). With this change, the IEnvironment parameter disappears from the RightsChecker class:
public sealed class RightsChecker
{
readonly IRightsService service;
public RightsChecker(IRightsService service)
{
this.service = service;
}
public void CheckRights()
{
if (!service.UserHasRights())
{
EnvironmentControl.Current.Exit(1);
}
}
}
But we still retain the ability to unit-test that it has been called:
public static void CheckRights_exits_program_when_user_has_no_rights()
{
var rightsService = new Mock<IRightsService>();
rightsService.Setup(foo => foo.UserHasRights()).Returns(false);
var enviromnent = new Mock<EnvironmentControl>();
EnvironmentControl.Current = enviromnent.Object;
try
{
var rightsChecker = new RightsChecker(rightsService.Object);
rightsChecker.CheckRights();
enviromnent.Verify(foo => foo.Exit(1));
}
finally
{
EnvironmentControl.ResetToDefault();
}
}
For more information about ambient contexts, see here.
I ended up creating a new method which I can then mock in my tests.
Code
public void CheckRights()
{
if(!service.UserHasRights())
{
Environment.Exit(1);
}
}
internal virtual void Exit()
{
Environment.Exit(1);
}
Unit test
[TestMethod]
public void TestCheckRightsWithoutRights()
{
MyService service = ...
service.When(svc => svc.Exit()).DoNotCallBase();
...
service.CheckRights();
service.Received(1).Exit();
}
If your goal is to avoid extra classes/interfaces just to support tests, how do you feel about Environment.Exit action via Property Injection?
class RightsChecker
{
public Action AccessDeniedAction { get; set; }
public RightsChecker(...)
{
...
AccessDeniedAction = () => Environment.Exit();
}
}
[Test]
public TestCheckRightsWithoutRights()
{
...
bool wasAccessDeniedActionExecuted = false;
rightsChecker.AccessDeniedAction = () => { wasAccessDeniedActionExecuted = true; }
...
Assert.That(wasAccessDeniedActionExecuted , Is.True);
}

How to return null when accessing a moq object?

I am using Moq library for unit testing. Now what i want is that when I access my object for the first time it should return null, and when i access this on second time it should return something else.
here is my code
var mock = new Mock<IMyClass>();
mock.Setup(?????);
mock.Setup(?????);
var actual = target.Method(mock.object);
in my method i am first checking that whether mock object is null or not, if it is null then do initialize it and then do some calls on it.
bool Method(IMyClass myObj)
{
if (myObj != null)
return true;
else
{
myObj = new MyClass();
bool result = myObj.SomeFunctionReturningBool();
return result;
}
}
what to do setup for mock object,
Also i need to know how to mock this line
bool result = myObj.SomeFunctionReturningBool();
It sounds like you are trying to run two tests with one test method - maybe it would be better to split the tests into two?
You also want to initialise a new object if the method is passed null. To test this, I suggest creating a factory object responsible for creating instances of MyClass. The new code would look like:
interface IMyClassFactory
{
IMyClass CreateMyClass();
}
bool Method(IMyClass myObj, IMyClassFactory myClassFactory)
{
if (myObj != null)
{
return true;
}
myObj = myClassFactory.CreateMyClass();
return myObj.SomeFunctionReturningBool();
}
Then the tests would look like:
[Test]
public void Method_ShouldReturnTrueIfNotPassedNull()
{
Assert.That(target.Method(new MyClass()), Is.True);
}
[Test]
public void Method_ShouldCreateObjectAndReturnResultOfSomeFunctionIfPassedNull()
{
// Arrange
bool expectedResult = false;
var mockMyClass = new Mock<IMyClass>();
mockMyClass.Setup(x => x.SomeFunctionReturningBool()).Returns(expectedResult);
var mockMyFactory = new Mock<IMyClassFactory>();
mockMyFactory.Setup(x => x.CreateMyClass()).Returns(mockMyClass.Object);
// Act
var result = target.Method(null, mockMyFactory.Object);
// Assert
mockMyClass.Verify(x => x.SomeFunctionReturningBool(), Times.Once());
mockMyFactory.Verify(x => x.CreateMyClass(), Times.Once());
Assert.That(result, Is.EqualTo(expectedResult));
}
Here the factory pattern has been used to pass in an object which can create objects of IMyClass type, and then the factory itself has been mocked.
If you do not want to change your method's signature, then create the factory in the class's constructor, and make it accessible via a public property of the class. It can then be overwritten in the test by the mock factory. This is called dependency injection.
Moq - Return null - This working example simply illustrates how to return null using Moq. While the line of code is required is the commented line below, a full working example is provided below.
// _mockShopService.Setup(x => x.GetProduct(It.IsAny<string>())).Returns(() => null);
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
public class Product
{
public string Id { get; set; }
public string Name { get; set; }
}
public interface IShopService
{
Product GetProduct(string productId);
}
public class ShopService : IShopService
{
public Product GetProduct(string productId)
{
if (string.IsNullOrWhiteSpace(productId))
{
return new Product();
}
return new Product { Id = "8160807887984", Name = "How to return null in Moq" };
}
}
public class Shop
{
private static IShopService _shopService;
public Shop(IShopService shopService)
{
_shopService = shopService;
}
public Product GetProduct(string productId)
{
Product product = _shopService.GetProduct(productId);
return product;
}
}
[TestClass]
public class ShopTests
{
Mock<IShopService> _mockShopService;
[TestInitialize]
public void Setup()
{
_mockShopService = new Mock<IShopService>();
}
[TestMethod]
public void ShopService_GetProduct_Returns_null()
{
//Arrange
Shop shop = new Shop(_mockShopService.Object);
//This is how we return null --- all other code above is to bring this line of code home
_mockShopService.Setup(x => x.GetProduct(It.IsAny<string>())).Returns(() => null);
//Act
var actual = shop.GetProduct(It.IsAny<string>());
//Assert
Assert.IsNull(actual);
}
}
To mock a result value you can do simply:
mock.Setup(foo => foo.SomeFunctionReturningBool()).Returns(true); // or false :)
for the other question, just pass null in the unit test instead of passing mock.object and your unit test cover that too. So you basically create two unit test one with:
var actual = target.Method(mock.object);
and the other one with:
var actual = target.Method(null);
Currently your SUT is tight-coupled with MyClass implementation. You can't mock objects which are instantiated with new keyword inside your SUT. Thus you cannot test your SUT in isolation, and your test is not unit test anymore. When implementation of MyClass.SomeFunctionReturningBool will change (it will return true instead of false), tests of your SUT will fail. This shouldn't happen. Thus, delegate creation to some dependency (factory) and inject that dependency to your SUT:
[Test]
public void ShouldReturnTrueWhenMyClassIsNotNull()
{
Mock<IMyClassFactory> factory = new Mock<IMyClassFactory>();
Mock<IMyClass> myClass = new Mock<IMyClass>();
var foo = new Foo(factory.Object);
Assert.True(foo.Method(myClass.Object));
}
[Test]
public void ShouldCreateNewMyClassAndReturnSomeFunctionValue()
{
bool expected = true;
Mock<IMyClass> myClass = new Mock<IMyClass>();
myClass.Setup(mc => mc.SomeFunctionReturningBool()).Returns(expected);
Mock<IMyClassFactory> factory = new Mock<IMyClassFactory>();
factory.Setup(f => f.CreateMyClass()).Returns(myClass.Object);
var foo = new Foo(factory.Object);
Assert.That(foo.Method(null), Is.EqualTo(expected));
factory.VerifyAll();
myClass.VerifyAll();
}
BTW assignment new value to method parameter does not affect reference which you passed to method.
Implementation:
public class Foo
{
private IMyClassFactory _factory;
public Foo(IMyClassFactory factory)
{
_factory = factory;
}
public bool Method(IMyClass myObj)
{
if (myObj != null)
return true;
return _factory.CreateMyClass().SomeFunctionReturningBool();
}
}
You can use TestFixture with parameter. this test will run two times and different type value.
using NUnit.Framework;
namespace Project.Tests
{
[TestFixture(1)]
[TestFixture(2)]
public class MyTest
{
private int _intType;
public MyTest(int type)
{
_intType = type;
}
[SetUp]
public void Setup()
{
if (_intType==1)
{
//Mock Return false
}
else
{
//Mock Return Value
}
}
}
}

Categories

Resources