Mam metodę tworzenia wydarzeń, które powinno zwrócić mi sentodto obiektu, używam fakeiteasy i tworzę obiekt z wartościami, ponieważ mają problemy z walidowaniem, teraz jest to mój kod. Jak powinienem zrobić ten test?

[Fact]
public async void CreateEventSuccess_should_return_the_object_created()
{
    var dataEventDto = A.Fake<EventDto>();
    var createEvent = A.Fake<IEventService>();
    var objectEventDtoReturn = new EventDto();
    var eventService = new EventService(this.eventRepository, this.mapper);

    dataEventDto.Title = "this is a test for add event";
    dataEventDto.Description = "this is a description for the add event";
    dataEventDto.Venue = "this is the street";
    dataEventDto.Date = DateTime.Now;
    dataEventDto.Booking = true;
    dataEventDto.TypeEvent = EventType.Presential;
    dataEventDto.State = EventState.Published;
    dataEventDto.CancellationReason = "this is a test of cancellation event";
    dataEventDto.Url = "this is a url";

    A.CallTo(() => createEvent.Add(dataEventDto)).Returns(objectEventDtoReturn);

    await eventService.Add(dataEventDto);

    A.CallTo(() => createEvent.Add(dataEventDto)).MustHaveHappened();
}

Błąd, że to produkt jest:

   Assertion failed for the following call:
        Assertion failed for the following call:
        Jalasoft.Events.Domain.Interfaces.Services.IService`2[Jalasoft.Events.Services.EventDto,System.String].Add(entity: Faked Jalasoft.Events.Services.EventDto)
      Expected to find it once or more but no calls were made to the fake object.

To jest temat, który testuję

private readonly IEventRepository repository;
private readonly IMapper mapper;
private EventValidator validator = new EventValidator();

public EventService(IEventRepository repository, IMapper mapper)
{
    this.repository = repository;
    this.mapper = mapper;
}

public async Task<EventDto> Add(EventDto entity)
{
    try
    {
        var results = this.validator.Validate(entity);
        bool success = results.IsValid;
        if (success)
        {
            Event eventMapper = this.mapper.Map<Event>(entity);
            var response = await this.repository.Add(eventMapper);
            EventDto eventDtoMapper = this.mapper.Map<EventDto>(response);
            return eventDtoMapper;
        }
        else
        {
            IList<ValidationFailure> failures = results.Errors;
            throw new ValidationException(failures);
        }
    }
    catch (Exception e)
    {
        throw new NotImplementedException(e.ToString());
    }
}

Dla Mappera, używam https://automapper.org/

Ieventservice Script.

public interface IEventService : IService<EventDto, string>
{
}

Skrypt Iservice.

public interface IService<T, TId>
    where T : EntityObject<TId>
{
    T GetById(TId id);

    Task<IEnumerable<T>> List();

    Task<T> Add(T entity);

    T Delete(T entity);

    T Edit(T entity);
}

Skrypt IevenPository

public interface IEventRepository : IRepository<Event, ObjectId>
{
}

Skrypt irePository

public interface IRepository<T, TId>
    where T : EntityObject<TId>
{
    T GetById(TId id);

    Task<IEnumerable<T>> List();

    Task<T> Add(T entity);

    T Delete(T entity);

    T Edit(T entity);
}

Skrypt EventValidator.

        public EventValidator()
        {
            this.RuleFor(x => x.Title)
                .NotNull()
                .Length(10, 50)
                .WithMessage("Title shuold be 50 characteres like Max");
            this.RuleFor(x => x.Description)
                .NotNull()
                .Length(10, 500)
                .WithMessage("Description shuold be 500 characteres like Max");
            this.RuleFor(x => x.Booking)
                .NotNull()
                .WithMessage("Booking not null");
            this.RuleFor(x => x.Date)
                .Must(this.BeAValidDate).
                WithMessage("Is not a valid datetime");
            this.RuleFor(x => x.State == EventState.Cancelled || x.State == EventState.Published)
                .NotNull()
                .WithMessage("Is not a valid state");
            this.RuleFor(x => x.TypeEvent == EventType.Online || x.TypeEvent == EventType.Presential)
                .NotNull()
                .WithMessage("Is not a valid event type");
        }
1
CoolLife 8 styczeń 2020, 02:54

1 odpowiedź

Najlepsza odpowiedź

Wydaje się, że bieżący test próbuje udać się z testem testowym.

Mock tylko zależności niezbędne do uzyskania testu pod testem, aby zachowywać się zgodnie z oczekiwaniami, gdy ćwiczy.

//...

[Fact]
public async Task CreateEventSuccess_should_return_the_object_created() {
    //Arrange

    //Making sure DTO can pass validation.
    var expected = new EventDto();
    expected.Title = "this is a test for add event";
    expected.Description = "this is a description for the add event";
    expected.Venue = "this is the street";
    expected.Date = DateTime.Now;
    expected.Booking = true;
    expected.TypeEvent = EventType.Presential;
    expected.State = EventState.Published;
    expected.CancellationReason = "this is a test of cancellation event";
    expected.Url = "this is a url";

    //mocked repository to verify expected behavior.
    IEventRepository eventRepository = A.Fake<IEventRepository>();
    Event passedEvent = null;
    A.CallTo(() => eventRepository.Add(A<Event>._))
        .Invokes((Event arg) => passedEvent = arg)
        .Returns(passedEvent);

    //Assuming an actual mapper is being used.
    var subject = new EventService(eventRepository, this.mapper);

    //Act
    EventDto actual = await subject.Add(expected);

    //Assert
    A.CallTo(() => eventRepository.Add(A<Event>._)).MustHaveHappened();

    //expected and actual should be equivalent, so that could also be checked

}
0
Nkosi 8 styczeń 2020, 02:30