mocking with moq and justmock

21
Mocking with Moq and JustMock Mocking tools for easier unit testing Learning & Development http://academy.telerik.com Telerik Software Academy

Upload: zeal

Post on 22-Feb-2016

121 views

Category:

Documents


0 download

DESCRIPTION

Mocking with Moq and JustMock. Mocking tools for easier unit testing. Learning & Development. http://academy.telerik.com. Telerik Software Academy. Table of Contents. Testable Code Mocking Moq JustMock. Testable Code. How to Write Testable Code. Inversion of Control Pattern - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Mocking with Moq and JustMock

Mocking with Moq and JustMock

Mocking tools for easier unit testing

Learning & Developmenthttp://academy.telerik.com

Telerik Software Academy

Page 2: Mocking with Moq and JustMock

Table of Contents

Testable Code Mocking Moq JustMock

2

Page 3: Mocking with Moq and JustMock

Testable Code

Page 4: Mocking with Moq and JustMock

How to Write Testable Code

Inversion of Control Pattern There is a decoupling of the execution of

a certain task from implementation Every module can focus on what it is

designed for Modules make no assumptions about

what other systems do but rely on their contracts

Replacing modules has no side effect on other modules

More info at http://en.wikipedia.org/wiki/Inversion_of_control

4

Page 5: Mocking with Moq and JustMock

How to Write Testable Code

Public API should work with interfaces, not implementation classes (IEnumerable vs. List)

Bad code:

Good code:

5

public IList<ICard> Cards { get; private set; }

public Card[] Cards { get; private set; }

Page 6: Mocking with Moq and JustMock

How to Write Testable Code

Dependency Injection Ninject – http://www.ninject.org/

Consists of: A dependent consumer A declaration of a component's

dependencies, defined as interface contracts

An injector (sometimes referred to as a provider or container) that creates instances of classes that implement a given dependency interface on request

6

Page 7: Mocking with Moq and JustMock

How to Write Testable Code

Bad:

7

public interface IViewBase {}public interface IPresenterBase {}public class MemoryLayoutView: IViewBase {}

public class MemoryLayoutPresenter: IPresenterBase{ private MemoryLayoutView view = new MemoryLayoutView(); public MemoryLayoutPresenter() { }}

Page 8: Mocking with Moq and JustMock

How to Write Testable Code Good:

8

public interface IViewBase {}public interface IPresenterBase {}public class MemoryLayoutView: IViewBase {}

public class MemoryLayoutPresenter : IPresenterBase{ private IViewBase view;

public MemoryLayoutPresenter(IViewBase myView) { this.view = myView; }}

public class Program { static void Main() {InjectionContainer.Create<typeof(MemoryLayoutPresenter)>(); }}

Page 9: Mocking with Moq and JustMock

Mocking

Page 10: Mocking with Moq and JustMock

Mocking

Makes Unit Testing more effective Avoid writing boring boilerplate

code Isolate dependencies among units Asserts expectations for code quality Ex: Checks that a method is called

only once10

Page 11: Mocking with Moq and JustMock

Moq

Page 12: Mocking with Moq and JustMock

Moq Install from the NuGet package manager

Refer the library Use its API https://github.com/Moq/moq4

12

var mock = new Mock<ICarsRepository>();mock.Setup(r => r.Add(It.IsAny<Car>())).Verifiable();mock.Setup(r => r.All()).Returns(this.FakeCarCollection);

Page 13: Mocking with Moq and JustMock

Moq The most often used APIs:

.Setup() .Verifiable() .Callback() .Returns() .Throws() It.Is<type>(x => condition)

13

Page 14: Mocking with Moq and JustMock

Telerik JustMock

Page 15: Mocking with Moq and JustMock

Telerik JustMock Install from the Telerik account

http://www.telerik.com/products/mocking.aspx

Use the Visual Studio NuGet package manager

15

CarsData = Mock.Create<ICarsRepository>();Mock.Arrange(() => CarsData.Add(Arg.IsAny<Car>())).DoNothing();Mock.Arrange(() => CarsData.All()).Returns(FakeCarCollection);Mock.Arrange(() => CarsData.Search(Arg.AnyString)) .Returns(FakeCarCollection.Where( c => c.Make == "BMW").ToList());Mock.Arrange(() => CarsData.GetById(Arg.AnyInt)) .Returns(FakeCarCollection.First());

Page 16: Mocking with Moq and JustMock

Telerik JustMock Two versions:

Free version – excellent when the code is written with testability in mind

Paid version – mocks everything (ex: mscorlib, EF, SQL), mocks legacy code base which is not written to be testable, statics, privates

More information here: http://

www.telerik.com/help/justmock/getting-started-commercial-vs-free-version.html

16

Page 17: Mocking with Moq and JustMock

Telerik JustMock The most often used APIs:

.CallOriginal() .Returns() .DoInstead() .DoNothing() .Throw() Arg.Matches<type>(x => condition)

17

Page 18: Mocking with Moq and JustMock

MockingLive Demo

Page 19: Mocking with Moq and JustMock

форум програмиране, форум уеб дизайнкурсове и уроци по програмиране, уеб дизайн – безплатно

програмиране за деца – безплатни курсове и уроцибезплатен SEO курс - оптимизация за търсачки

уроци по уеб дизайн, HTML, CSS, JavaScript, Photoshop

уроци по програмиране и уеб дизайн за ученициASP.NET MVC курс – HTML, SQL, C#, .NET, ASP.NET MVC

безплатен курс "Разработка на софтуер в cloud среда"

BG Coder - онлайн състезателна система - online judge

курсове и уроци по програмиране, книги – безплатно от Наков

безплатен курс "Качествен програмен код"

алго академия – състезателно програмиране, състезанияASP.NET курс - уеб програмиране, бази данни, C#, .NET, ASP.NET

курсове и уроци по програмиране – Телерик академия

курс мобилни приложения с iPhone, Android, WP7, PhoneGapfree C# book, безплатна книга C#, книга Java, книга C# Дончо Минков - сайт за програмиране

Николай Костов - блог за програмиранеC# курс, програмиране, безплатно

?? ? ?

??? ?

?

? ?

??

?

?

? ?

Questions?

?форум програмиране, форум уеб дизайн

курсове и уроци по програмиране, уеб дизайн – безплатно

програмиране за деца – безплатни курсове и уроцибезплатен SEO курс - оптимизация за търсачки

уроци по уеб дизайн, HTML, CSS, JavaScript, Photoshop

уроци по програмиране и уеб дизайн за ученициASP.NET MVC курс – HTML, SQL, C#, .NET, ASP.NET MVC

безплатен курс "Разработка на софтуер в cloud среда"

BG Coder - онлайн състезателна система - online judge

курсове и уроци по програмиране, книги – безплатно от Наков

безплатен курс "Качествен програмен код"

алго академия – състезателно програмиране, състезанияASP.NET курс - уеб програмиране, бази данни, C#, .NET, ASP.NET

курсове и уроци по програмиране – Телерик академия

курс мобилни приложения с iPhone, Android, WP7, PhoneGapfree C# book, безплатна книга C#, книга Java, книга C# Дончо Минков - сайт за програмиране

Николай Костов - блог за програмиранеC# курс, програмиране, безплатно

?? ? ?

??? ?

?

? ?

??

?

?

? ?

Questions?

?

Mocking with Moq and JustMock

http://academy.telerik.com

Page 20: Mocking with Moq and JustMock

Free Trainings @ Telerik Academy

C# Programming @ Telerik Academy csharpfundamentals.telerik.com

Telerik Software Academy academy.telerik.com

Telerik Academy @ Facebook facebook.com/TelerikAcademy

Telerik Software Academy Forums forums.academy.telerik.com 20

Page 21: Mocking with Moq and JustMock

Homework Finish the unit testing for CarsController

Write mocks for the rest of ICarsRepository interface (sorting)

Write missing unit test so that the controller functionality is fully tested

21