Pregunta

I'm trying to create a mole for the System.Security.Cryptography.CspParameters class, more specifically for the KeyContainerName. The problem is, the moles delegate for it doesn't show up in Intellisense. Here's the code I'm using:

MCspParameters.AllInstances.KeyContainerNameSetString = (
    CspParameters parameters, 
    string name) =>
{
   // ...
}

The KeyContainerNameSetString is not actually available. I think this is because KeyContainerName is a field and not a property.

Any ideas on how I can Mole this field so I can test it?

¿Fue útil?

Solución

A field is writable by default so it is not necessary to use Moles in that case, just set it to the value you want.

cspParameters.KeyContainerName = "MyContainerName";

However, since you are using MCspParameters.AllInstances I'll assume that the CspParameters instance you want to mole is created outside of your control and you cannot set it before it being used.

In that case you can mole the constructor that is called by every other constructor of that class and just set the field in the question to your specific value. Something like this:

[TestMethod()]
[HostType("Moles")]
public void Test()
{
    MCspParameters.ConstructorInt32StringStringCspProviderFlags = (
        p, 
        providerType, 
        providerName, 
        keyContainerName, 
        flags) => 
    {
        p.ProviderType = providerType;
        p.ProviderName = providerName;
        p.KeyContainerName = "MyContainerName";
        p.KeyNumber = -1;
        p.Flags = flags;
    };

    CspParameters cspParameters = new CspParameters(1);

    Assert.AreEqual(cspParameters.ProviderType, 1);
    Assert.AreEqual(cspParameters.KeyContainerName, "MyContainerName");
}

Otros consejos

There seems to be no way to detour a public field. So if you want to make sure that a particular field has been set to some value - you're out of luck. I guess as a workaround you could create a wrapper for the CspParameters class which has a property corresponding to each field of it and use the wrapper wherever you can in your program and detour the properties in your tests.

You probably could also implement implicit conversion from your wrapper to CspParameters to be able to pass your wrapper where an instance of CspParameters is required.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top