Git Product home page Git Product logo

unit-testing-beispiel's Introduction

Cheat sheet

AutoFixture

Create Fixture

// create fixture
var fixture = new Fixture();

// create model
var model = fixture.Create<Level4Model>();

Customize Fixture

// change only for this creation
var person = fixture.Build<Person>()
    .With(x => x.Age, 28)
    .Create();
 
 // change for all calls
 fixture.Customize<Person>(c => c.With(x => x.FirstName, "Paul"));
 var person = fixture.Create<Person>();
 
 // omit values (setting null value)
 var model = fixture.Build<TestModel>()
    .Without(e => e.Test)
    .Create();

Freeze

var fixture = new Fixture();
// freeze strings with "Name"
var expectedName = fixture.Freeze("Name");
...

AutoData

// Creates a fixture of Myclass automatically
[Theory, AutoData]
public void Test_WithAutoData(Myclass myClass)

Moq

Create Mock

// create and get mock (for setup)
var mock = new Mock<IFoo>();

// Create and get object
var object = Mock.Of<Object>();

Setup

mock.Setup(foo => foo.DoSomething("ping")).Returns(true);

// use parameter in return value
mock.Setup(x => x.DoSomethingStringy(It.IsAny<string>())).Returns((string s) => s.ToLower());

Argument matcher

// any value
mock.Setup(foo => foo.DoSomething(It.IsAny<string>())).Returns(true);

// matching Func<int>, lazy evaluated
mock.Setup(foo => foo.Add(It.Is<int>(i => i % 2 == 0).Returns(true);

// matching ranges
mock.Setup(foo => foo.Add(It.IsInRange<int>(0, 10, Range.Inclusive))).Returns(true);

// matching regex
mock.Setup(x => x.DoSomethingStringy(It.IsRegex("[a-d]+", RegexOptions.IgnoreCase))).Returns("foo");

Throwing exceptions

// Throw InvaldOperationException with parameter "reset"
mock.Setup(foo => foo.DoSomething("reset").Throws<InvalidOperationException>();

// Throw ArgumentException if parameter is empty
mock.Setup(foo => foo.DoSomething("").Throws(new ArgumentException("command"));

Async functions

mock.Setup(foo => foo.DoSomethingAsync()).ReturnsAsync(true);

// Mocking DbSet without IAsyncEnumerable with Moq.EntityFrameworkCore
var entity = new MODEL;
mock.Setup(foo => foo.Set<MODEL>()).ReturnsDbSet(new[] { entity });

// Mocking Queryables with ToListAsync, etc. with MockQueryable.Moq
var users = new List<UserEntity> 
{
    new UserEntity { Id = userId, ...}
  ... etc. 
};

var mock = users.AsQueryable().BuildMock();

_dbContextMock.Setup(ctx => ctx.SetQueryable<UserEntity>()).Returns(mock.Object);

Verify Mocks

// called once
mock.Verify(foo => foo.DoSomething("ping"));

// Verify with custom error message for failure
mock.Verify(foo => foo.DoSomething("ping"), "When doing operation X, the service should be pinged always");

// Method should never be called
mock.Verify(foo => foo.DoSomething("ping"), Times.Never());

AutoMoqData

// Custom attribute for AutoMoq
public class AutoMoqDataAttribute : AutoDataAttribute
{
    public AutoMoqDataAttribute()
        : base(new Fixture()
            .Customize(new AutoMoqCustomization()))
    {
    }
}

Frozen

// Freeze object in test parameters
[Theory, AutoMoqData]
public void Test_WithAutoData([Frozen]Mock<IService> serviceMock)

unit-testing-beispiel's People

Contributors

nbyx avatar sebastian-siebert avatar sebastiansiebert avatar

Stargazers

 avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.