![](/img/trans.png)
[英]How can I fake a DbSet<T> using FakeItEasy when the classes are internal?
[英]FakeItEasy class containing fake method not recognized as a fake object problem
我有這段代碼:
[Fact]
public async Task AnnouncerIndex_Test_1()
{
//Arrange
var fakeContext = A.Fake<OrganizerDbContext>();
var fakeUserManager = A.Fake< UserManager<AppUser>>();
var controller = new AnnouncementsController(fakeContext, fakeUserManager);
A.CallTo(() => controller
.IsUserBlockedFromAccesingAnnouncer("aaa"))
.Returns(Task.FromResult(false));
//Act
//some code
//Assert
//some code
}
我想對我的 controller 中的方法運行單元測試,我正在測試的方法調用另一個方法,我想用使用 A.CallTo(()=>) 的預定義方法替換它返回的值。 但是相反,我被告知經過測試的 controller 不是假的 object,在運行測試后我得到了這個摘要:
System.ArgumentException : Object 'Organizer3.Controllers.AnnouncementsController' of type Organizer3.Controllers.AnnouncementsController is not recognized as a fake object.
Stack Trace:
DefaultFakeManagerAccessor.GetFakeManager(Object proxy) line 28
Fake.GetFakeManager(Object fakedObject) line 28
FakeConfigurationManager.GuardAgainstNonFake(Object target) line 83
FakeConfigurationManager.CallTo[T](Expression`1 callSpecification) line 45
A.CallTo[T](Expression`1 callSpecification) line 161
AnnouncementsControllerTests.AnnouncerIndex_Test_1() line 32
--- End of stack trace from previous location ---
我還嘗試創建假的 controller,但這樣做並不允許我測試其中的方法。
var fakeController =A.Fake<AnnouncementsController>();
A.CallTo(() => fakeController
.IsUserBlockedFromAccesingAnnouncer("aaa"))
.Returns(Task.FromResult(false));
測試總結:
FakeItEasy.Configuration.FakeConfigurationException :
The current proxy generator can not intercept the method Organizer3.Controllers.AnnouncementsController.IsUserBlockedFromAccesingAnnouncer(System.String CUID) for the following reason:
- Non-virtual members can not be intercepted. Only interface members and virtual, overriding, and abstract members can be intercepted.
Stack Trace:
DefaultInterceptionAsserter.AssertThatMethodCanBeInterceptedOnInstance(MethodInfo method, Object callTarget) line 23
FakeConfigurationManager.AssertThatMemberCanBeIntercepted(ParsedCallExpression parsed) line 96
FakeConfigurationManager.CallTo[T](Expression`1 callSpecification) line 46
A.CallTo[T](Expression`1 callSpecification) line 161
AnnouncementsControllerTests.AnnouncerIndex_Test_1() line 36
--- End of stack trace from previous location ---
您的第一次嘗試沒有成功,因為如錯誤消息所述,您的new AnnouncementsController
不是假的,它是 class 的實際實例,因此 FakeItEasy 無法對其進行配置。
第二次嘗試(使用偽造的AnnouncementsController
)可能會奏效,但您需要更改IsUserBlockedFromAccesingAnnouncer
以使其成為虛擬的,以便 FakeItEasy 可以偽造它。 此外,您還需要將偽造的依賴項傳遞給它,如下所示:
var fakeController = A.Fake<AnnouncementsController>(options =>
options.WithArgumentsForConstructor(() => new AnnouncementsController(fakeContext, fakeUserManager)));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.