Moq And Unit Test

Moq and unit test

Hello everybody,

today I want to write few words about Moq and unit testing. 

First of all you can have a question, why do I need Moq at all?

Moq is especially useful for cases if we don't have desire to code interface, then code implementation of interface, and then code fake implementation. As usually those simple implementation are relatively simple so somebody ( as Moq team ) can organize code generation for your simple interface implementations.

So, unit test is something that should follow 3 A:

  1. Arrange
  2. Act
  3. Assert

General schema of Unit test implementation can be like this:

        [Test]
        public void SomeTest()
        {
            //Arrange
            var mockRepository = new Mock<IBaseInterface>();
            mockRepository.Setup(x => x.FunctionInIBaseInterface(It.IsAny<SomeClass>()));
            
            var classWhichUsesImplementationOfinterface = new ClassWhichUsesImplementationOfinterface (mockRepository.Object);

            //Act
            classWhichUsesImplementationOfinterface.Create(new SomeClassWithEmptConstructor());

            //Assert
            mockRepository.VerifyAll();
        }            

The most intersting part for me was mockRepository.Setup(x => x.FunctionInIBaseInterface(It.IsAny<SomeClass>())); Setup here can be considered as saying: setup this expectation.  This code arranges setup for a calling to a void method. But void method inside of it should call function FunctionInIBaseInterface.  In other case unit test will fail.

How many times some function was executed. 

 someRepository.Verify(x=>x.SomeFunction(It.IsAny<SomeClass>()), Times.Exactly(5));

This code will check that SomeFunction was executed exactly 5 times and it expects instane of any SomeClass class.

Another usefull functions for unit testing

Setup function after dot has interesting list. 

I'll mention them from simplest ( from my viewpoint ) to most complicated.

mockRepository

                    .Setup(x => x.TryParse(It.IsAny<string>(), out address))

                    .Returns(true);

this setup will configure expectation that function TryParse will be executed and expects that function TryParse will return true.

In order to execute it your implementation should call this function.

Very surprising is usage of Callback. Look at this code:

var i = 1;

mockIdFactory.Setup(x => x.Create())

       .Returns(() => i)

       .Callback(() => i++);

This code will cause passing Create vales for mockIdFactory not just one value, but ints which will be incremented one by one.

No Comments

Add a Comment
Comments are closed