第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機(jī)立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何為帶有兩個參數(shù)的Controller方法編寫單元測試以及需要測試哪些場景?

如何為帶有兩個參數(shù)的Controller方法編寫單元測試以及需要測試哪些場景?

C#
慕尼黑8549860 2021-06-03 18:01:03
我是單元測試的新手。我想為刪除控制器操作編寫單元測試。我想使用 NSubstitute 來模擬所有依賴項。當(dāng)前的實(shí)現(xiàn)是使用接口 IRepository 來抽象出對底層數(shù)據(jù)源的調(diào)用??刂破鱬ublic ActionResult Delete(string fileName, bool isPublic){    try    {        repo.DeleteDocument(new PortalDocument        {            Path = fileName,            IsPublic = isPublic        });    }    catch (Exception e)    {        EventLog.Logger.LogCritical(e, e.Message);                }    return RedirectToAction(IndexViewName);}存儲庫接口。public interface IRepository<out T> where T:     CloudBlobContainer{    bool DeleteDocument(PortalDocument document);}門戶文檔類public class PortalDocument{    public bool IsPublic { get; set; }}提前致謝。
查看完整描述

1 回答

?
人到中年有點(diǎn)甜

TA貢獻(xiàn)1895條經(jīng)驗(yàn) 獲得超7個贊

我想你已經(jīng)找到了快樂路徑場景,測試在沒有例外的情況下會發(fā)生什么。但是現(xiàn)在您需要測試不愉快的路徑,當(dāng)拋出異常時它的行為是否正確。


//arrange

var mockRepo = new Mock<DocumentRepository>(MockBehavior.Strict);

mockRepo.Setup(r => r.DeleteDocument(It.IsAny<PortalDocument>())).Throws(new Exception("test"));


var controller = new DocumentController(mockRepo.Object);


//act

var result = controller.Delete("filename", true);



//assert

//make sure result is a redirect result

//but how do I test that it got logged?

不幸的是,您會發(fā)現(xiàn)您實(shí)際上無法測試您是否記錄了某些內(nèi)容。為什么?因?yàn)槟阌幸粋€靜態(tài)方法調(diào)用。靜態(tài)方法調(diào)用不可測試。相反,您應(yīng)該遵循依賴倒置原則。


解決此問題的一種方法是用可注入的東西包裝您的日志記錄調(diào)用。


public interface ILogger

{

    void LogCritical(Exception exception);

}


public class EventLogLogger : ILogger

{

    public void LogCritical(Exception exception)

    {

        EventLog.Logger.LogCritical(exception, exception.Message); 

    }

}

然后你的單元測試變成:


//arrange

var mockRepo = new Mock<IDocumentRepository>(MockBehavior.Strict);

mockRepo.Setup(r => r.DeleteDocument(It.IsAny<PortalDocument>())).Throws(new Exception("test"));


var mockLogger = new Mock<ILogger>(MockBehavior.Strict);

mockLogger.Setup(l => l.LogCritical(It.IsAny<Exception>())).Verifiable;


var controller = new DocumentController(mockRepo.Object, mockLogger.Object);


//act

var result = controller.Delete("filename", true);



//assert

//make sure result is a redirect result

mockLogger.Verify();

請注意,我在示例中使用了Moq 庫語法。您需要根據(jù)您的模擬框架進(jìn)行調(diào)整。


如果您不熟悉依賴注入,我強(qiáng)烈建議您觀看Miguel Castro 的 Deep Dive Into Dependency Injection 和 Writing Quality Decoupled Code。



查看完整回答
反對 回復(fù) 2021-06-05
  • 1 回答
  • 0 關(guān)注
  • 253 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號