0

I want to test in my MVC app if I can create an object using xUnit. The create method in my repository looks like this:


public bool Create(Patient model)
{
    try {
        _db.patients.Add(model);
        saveChanges();
        return true
    } catch {
        return false;
    }    
}

public int saveChanges() {   
    return db.SaveChanges();
}

My test currently looks like this:

public void CanCreatePatient() {
    using(var mock = AutoMock.GetLoose())
    {
        mock.Mock<IPatientRepo>().Setup(x => x.Create(GetSamplePatient()));
        mock.Mock<IPatientRepo>().Setup(x => x.saveChanges()),Returns(1);

        var cls = mock.Mock.Create<IPatientRepo>();

        var actual = cls.Create(GetSamplePatient());

        Assert.True(actual);
    }
}

Im fairly new to xUnit and testing in dotnet. Currently this test always fails because the actual returns false. What can I do to solve this issue?

JDausyd
  • 17
  • 2
  • 2
    You mock the class you want to test that can't work. if you want to test your concrete IPatientRepo class Create method then use that concrete class and mock the dependencies of that class. In this case presumably whats behind db (or _db). – Ralf Jan 03 '23 at 16:08
  • 1
    If you want to mock a method inside a concrete class, you need to : mark all the methods you'll want to mock virtual, then, mock the concrete type, not the interface. Otherwise, the mock will never know to redirect the call to the real implementation – Irwene Jan 03 '23 at 16:10
  • 1
    Example using Moq : https://stackoverflow.com/a/2462672/2245256 – Irwene Jan 03 '23 at 16:11

0 Answers0