Warum passiert das und wie kann ich das richtig überprüfen?
private IDictionary<string, string> knownContentTypes;
public ContentTypeDictionaryService(IDictionary<string, string> contentTypesDictionary) {
this.knownContentTypes = contentTypesDictionary;
}
public bool TryGetExtension() {
var a = (knownContentTypes == null); // a is false
var x = knownContentTypes.Any(); // this throws NullReferenceException.
}
BEARBEITEN Vollständiger Code:
public class ContentTypeDictionaryService : ContentTypeService {
private IDictionary<string, string> knownContentTypes;
public ContentTypeDictionaryService(IDictionary<string, string> contentTypesDictionary) {
if (contentTypesDictionary == null) throw new ArgumentNullException("contentTypesDictionary");
this.knownContentTypes = contentTypesDictionary;
}
public bool TryGetExtension(string contentType, out string extension) {
if (String.IsNullOrEmpty(contentType)) throw new ArgumentNullException("contentType");
var a = knownContentTypes == null; // false
var x = knownContentTypes.Any(); // An exception of type "System.NullReferenceException" occurred in System.Core.dll but was not handled in user code Additional information: Object reference not set to an instance of an object. (not inner exception)
return extension != default(string);
}
}
[TestMethod]
public void WeirdTest() {
string extension;
var contentTypesDictionaryMock = new Mock<Dictionary<string, string>>();
contentTypeService = new Mock<ContentTypeDictionaryService>(contentTypesDictionaryMock.Object);
contentTypeService.TryGetExtension("image/png", out extension)
}
EDIT 2:
Wie soll ich das Wörterbuch verspotten? Ich verwende Moq.
Antworten:
2 für die Antwort № 1Dein Spott kehrt zurück null
Wenn die Erweiterungsmethode aufgerufen wird GetEnumerator()
.
Du brauchst etwas wie
contentTypesDictionaryMock.Setup(x=>x.GetEnumerator()).Returns(new DictionaryEnumerator());
Ersetzen Sie DictionaryEnumerator () durch etwas, das existiert. Alternativ kann das Wörterbuch nicht nachgeahmt werden, da dies nicht zu Nebenwirkungen führt.