简体   繁体   中英

Unit Testing with Mock. Parent does not have a default constructor

I'm trying to write a unit test and coming across the error,

Parent does not have a default constructor. The default constructor must be explicitly defined.

I've had a look to see what this means and I see it mentioned that there is no public constructor. Only thing is, my code does have this so I'm confused why there is this error.

This is the unit test..

public void CalculateVat_ReturnsCorrectAmount()
{
    // Arrange
    const decimal expectedResult = 2;

    _mockSingleValueParameter = new Mock<ISingleValueParameterService>();
    _mockItemCache = new Mock<ItemCache>();
    _mockReferenceDataService = new Mock<ReferenceDataService>();

    _Calculator = new CostCalculator(_mockSingleValueParameter.Object, _mockItemCache.Object,
        _mockReferenceDataService.Object);
    // end

    //.....    
}

The line

_calculator = new CostCalculator(_mockSingleValueParameter.Object, _mockItemCache.Object,
            _mockReferenceDataService.Object)

is the one that throws the error.

This is the constructor of CostCalculator ..

public CostCalculator(
    ISingleValueParameterService singleValueParameterService, ItemCache cache, ReferenceDataService referenceDataService);
{
    _itemCache = cache;
    _singleValueParamService = singleValueParameterService;
    _refDataService = referenceDataService;
}

There is other code in the project that looks just like this as well but works..I can't understand what the difference is between them.

TIA!

If you want to mock a concrete class instead of an interface, it must have a default constructor (ie no parameters) and any methods you want to perform setups on must be virtual.

In your case it looks like either ItemCache or ReferenceDataService (or both) are lacking default constructors.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM