์๋
,
autofixture๋ฅผ ์ฌ์ฉํ์ฌ Dictionary<T, U>
๋ฅผ ์์ฑํ๋ฉด ๊ธฐ๋ณธ์ ์ผ๋ก ๊ฐ์ด ์ฑ์์ง์ง๋ง ConcurrentDictionary<T, U>
์์๋ ๊ทธ๋ ์ง ์์ต๋๋ค.
์ด๊ฒ์ ์๋์ ์ผ๋ก ์ค๊ณ๋ ๊ฒ์ด๋ฉฐ ์ํ ๋น๋๋ฅผ ์ฌ์ฉํ์ฌ ํด๋น ๋์์ ์ง์ ๋ณ๊ฒฝํด์ผ ํฉ๋๊น, ์๋๋ฉด ๋๋ฝ๋ ๊ธฐ๋ฅ์ด๋ ๋ฒ๊ทธ์ ๋๊น?
๋ค๋ฅธ ์ฌ๋์ด ๊ฐ์ ๋ฌธ์ ์ ์ง๋ฉดํ๋ฉด ์ด์ ๋ํ ๊ฒฌ๋ณธ ์์ฑ๊ธฐ๋ฅผ ์์ฑํ์ต๋๋ค.
public class ConcurrentDictionaryGenerator : ISpecimenBuilder
{
public object Create(object request, ISpecimenContext context)
{
Type type = request as Type;
if (type == null)
{
return new NoSpecimen();
}
Type[] typeArguments = type.GetTypeInfo().GetGenericArguments();
if (typeArguments.Length != 2 || typeof(ConcurrentDictionary<,>).MakeGenericType(typeArguments) != type)
{
return new NoSpecimen();
}
Type nonConcurrentDictionaryType = typeof(Dictionary<,>).MakeGenericType(typeArguments);
IDictionary nonConcurrentDictionary = (IDictionary) context.Resolve(nonConcurrentDictionaryType);
IDictionary concurrentDictionary = (IDictionary) Activator.CreateInstance(type);
foreach (object key in nonConcurrentDictionary.Keys)
{
object value = nonConcurrentDictionary[key];
concurrentDictionary.Add(key, value);
}
return concurrentDictionary;
}
}
์๋
ํ์ธ์,
๊ทธ ์ด์ ๋ฅผ ๋งํ ์๋ ์์ง๋ง ์์ค ์ฝ๋๋ฅผ ๋ณด๋ฉด ์ง์๋๋ ์ปฌ๋ ์
์ด ํ๋ ์ฝ๋ฉ๋์ด ์์ต๋๋ค.
๋ฐ๋ผ์ "์ ํ์ด IDictionary๋ฅผ ๊ตฌํํฉ๋๊น?"์ ๊ฐ์ ๊ฒ์ด ์๋๋ผ "์ ํ ์ฌ์ <,>์
๋๋ค."์
๋๋ค. ๋ฐ๋ผ์ ConcurrentDictionary๋ ์๋ํ์ง ์์ต๋๋ค.
์์ ์ ๊ฒฌ๋ณธ ์ ์๊ธฐ๋ฅผ ๋ง๋ค ํ์๊ฐ ์์ต๋๋ค. ์ด๋ฏธ ์๋ ๊ฒ์ ์ฌ์ฉํ ์ ์์ต๋๋ค.
var fixture = new Fixture();
var query = new ModestConstructorQuery();
var methodInvoker = new MethodInvoker(query);
var dictionaryFiller = new DictionaryFiller();
var postProcessor = new Postprocessor(methodInvoker, dictionaryFiller);
var exactTypeSpecification = new ExactTypeSpecification(typeof(ConcurrentDictionary<,>));
var specimenBuilder = new FilteringSpecimenBuilder(postProcessor, exactTypeSpecification);
fixture.Customizations.Add(specimenBuilder);
์ด ๋ผ์ด๋ธ๋ฌ๋ฆฌ์ ๋ด๋ถ์ ๋ํด ๋ ๋ง์ด ์์๋ก ๋ ์ข์ํฉ๋๋ค.
ํ์ฌ Dictionary<,>
์๋ง ์๋ค๋ ์ฌ์ค์ด ํฅ๋ฏธ๋กญ๊ณ ๋ด์ฅ๋ ๋ฐฉ๋ฒ์ ๊ฐ์ฌ๋๋ฆฝ๋๋ค!
๋๊ตฐ๊ฐ์๊ฒ ๋จ์ ์ ์ผํ ์ง๋ฌธ์ ๋ค์๊ณผ ๊ฐ์ต๋๋ค. ์ถ๊ฐํ๊ธฐ์ ์ข์ ๊ธฐ๋ฅ์ด ๋ ๊น์? ๊ตฌ์ฒด์ ์ผ๋ก ConcurrentDictionary<,>
๊ฐ ์๋๋ผ ๋ชจ๋ IDictionary<,>
๊ตฌํ์ ์ ์ฉ๋ฉ๋๊น?
์ ๊ฐ ์๋ชป๋ ์ ๋ณด๋ฅผ ํผ๋จ๋ฆฌ์ง ์๋ ๊ฒ์, Dictionary<,> ๋ฟ๋ง์ด ์๋๋๋ค. Fixture.cs์์ ์ง์ ์ ํ ๋ชฉ๋ก์ ์ฐพ์ ์ ์๋ค๋ ์ ์ ์ง์ ํ๊ณ ์ถ์์ต๋๋ค. ์๋ฅผ ๋ค์ด SortedDictionary<,>์ด๊ธฐ๋ ํ์ง๋ง ์ด๋ฏธ ์๊ณ ์๋ ๊ฒ์ฒ๋ผ ConcurrentDictionary<,>๊ฐ ์๋๋๋ค.
๋ฐ๋์ ๋ฏธ๋์ ๊ตฌํ์ ์ธํฐํ์ด์ค๋ฅผ ํ์ธํด์ผ ํ๋ค๊ณ ๋งํ๊ณ ์ถ์ต๋๋ค.
์ค์ ๋ก ํ๋์ฝ๋ฉ๋ ๊ฒ์ ์ง์์ด ์๋๋ผ ์ธํฐํ์ด์ค๊ฐ ํน์ ์ ํ์ผ๋ก ์ค๊ณ๋๋ค๋ ์ฌ์ค์ ๋๋ค. IDictionary ๋ฐ IReadOnlyDictionary์ ๋ง์ฐฌ๊ฐ์ง๋ก Dictionary์ ๋ฆด๋ ์ด๋๋ ์์ ๋๋ค.
๊ฐ์ฅ ์ ์ฉํ ๋๊ธ
์๋ ํ์ธ์,
๊ทธ ์ด์ ๋ฅผ ๋งํ ์๋ ์์ง๋ง ์์ค ์ฝ๋๋ฅผ ๋ณด๋ฉด ์ง์๋๋ ์ปฌ๋ ์ ์ด ํ๋ ์ฝ๋ฉ๋์ด ์์ต๋๋ค.
๋ฐ๋ผ์ "์ ํ์ด IDictionary๋ฅผ ๊ตฌํํฉ๋๊น?"์ ๊ฐ์ ๊ฒ์ด ์๋๋ผ "์ ํ ์ฌ์ <,>์ ๋๋ค."์ ๋๋ค. ๋ฐ๋ผ์ ConcurrentDictionary๋ ์๋ํ์ง ์์ต๋๋ค.
์์ ์ ๊ฒฌ๋ณธ ์ ์๊ธฐ๋ฅผ ๋ง๋ค ํ์๊ฐ ์์ต๋๋ค. ์ด๋ฏธ ์๋ ๊ฒ์ ์ฌ์ฉํ ์ ์์ต๋๋ค.