CodeLearner
CodeLearner

Reputation: 439

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!

Upvotes: 7

Views: 9443

Answers (1)

Owen Pauling
Owen Pauling

Reputation: 11871

If you want to mock a concrete class instead of an interface, it must have a default constructor (i.e. 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.

Upvotes: 2

Related Questions