Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Moq

USAMI Kosuke
December 09, 2017

 Moq

USAMI Kosuke

December 09, 2017
Tweet

More Decks by USAMI Kosuke

Other Decks in Programming

Transcript

  1. ϥΠϒϥϦ » OCMock : iOS (Objective-C) » Mockito : Android

    (Java / Kotlin) » Moq : .NET / Xamarin (C#)
  2. Moq

  3. Moq ͷ࢖͍ํ public interface IHoge { bool DoSomething(string value); }

    var mock = new Mock<IHoge>(); // interface ͕ࣗಈతʹ࣮૷͞ΕΔ mock.Object.DoSomething("abc"); // -> false
  4. ஫ҙ (1) interface ͕ඞཁ » ஔ͖׵͍͑ͨΦϒδΣΫτͷ interface Λఆٛ͢Δ » ຊ෺ͷ

    class ͸ͦͷ interface Λ࣮૷͢Δ » ςετμϒϧ΋ͦͷ interface Λ࣮૷͢Δ » ࢀߟ : ຊ෺ͷ class Λܧঝͯ͠ςετμϒϧʹ͢Δख΋͋Δ
  5. ྫɿݻఆ஋Λฦ͢ϓϩύςΟ public interface IHoge { string Name { get; }

    } var mock = new Mock<IHoge>(); mock.SetupGet(x => x.Name) .Returns("xyz"); var name = mock.Object.Name; // -> "xyz"
  6. ྫɿSet ՄೳͳϓϩύςΟ public interface IHoge { string Name { get;

    set; } } var mock = new Mock<IHoge>(); mock.SetupProperty(x => x.Name, "xyz"); mock.Object.Name = "123"; var name = mock.Object.Name; // -> "123"
  7. ྫɿಛఆͷೖྗʹಛఆͷग़ྗΛฦ͢ public interface IHoge { bool DoSomething(string value); } var

    mock = new Mock<IHoge>(); mock.Setup(x => x.DoSomething("abc")) .Returns(true); mock.Object.DoSomething("abc"); // -> true
  8. ྫɿೖྗͷ৚݅Λࢦఆ͢Δ public interface IHoge { bool DoSomething(string value); } var

    mock = new Mock<IHoge>(); mock.Setup(x => x.DoSomething(It.Is<string>(s => s.Length < 10))) .Returns(true); mock.Object.DoSomething("abc"); // -> true
  9. ྫɿೖྗ಺༰ʹԠͨ͡ग़ྗΛฦ͢ public interface IHoge { string DoSomething(string value); } var

    mock = new Mock<IHoge>(); mock.Setup(x => x.DoSomething(It.IsAny<string>())) .Returns(s => s.ToUpper()); mock.Object.DoSomething("abc"); // -> "ABC"
  10. ςετίʔυ͔Βͷ࢖͍ํ » ࣄલ४උ » Mock ΠϯελϯεΛੜ੒ » Setup ΛͣΒͣΒͱॻ͘ »

    mock.Object Λऔಘ͢Δ » ςετର৅͸࣮ࡍͷΦϒδΣΫτͷ୅ΘΓʹ mock.Object Λ࢖͏
  11. ஫ҙ (2) ґଘΦϒδΣΫτͷࠩ͠ସ͑ » ςετର৅͸ class Ͱ͸ͳ͘ interface ʹґଘ͢Δ͜ͱ »

    ຊ෺ͷΦϒδΣΫτΛςετμϒϧʹࠩ͠ସ͑ΒΕΔΑ͏ʹ͢Δ͜ͱ » ίϯετϥΫλͰ౉͢ɺDI ίϯςφΛ࢖͏ɺɾɾɾ
  12. ྫɿϓϩύςΟͷఆٛΛָʹ͢Δ public interface IHoge { string Name { get; set;

    } } var mock = new Mock<IHoge>(); mock.SetupAllProperties();
  13. ྫɿྫ֎Λൃੜͤ͞Δ public interface IHoge { bool DoSomething(string value); } var

    mock = new Mock<IHoge>(); mock.Setup(x => x.DoSomething("abc")) .Throws<InvalidOperationException>();
  14. ྫɿݺͼग़͞ΕͨࡍͷॲཧΛهड़͢Δ var mock = new Mock<IHoge>(); mock.Setup(x => x.DoSomething("abc")) .Callback(()

    => Console.WriteLine("Before returns")) .Returns(true) .Callback(() => Console.WriteLine("After returns"));