Assert.IsInstanceOfType 不接受类型作为参数

Assert.IsInstanceOfType won't accept Type as argument

我正在尝试测试某些对象是否属于特定类型:

 [TestInitialize]
        public void SetUp()
        {
            exam = new Exam(examId, name, date, templateId);

            tabViewModel = new TabControlViewModel(exam);

            tabs = new List<SingleTabViewModel>(tabViewModel.Tabs);

            // Not using this in the current code, but including here to make
            // clear the expected type of the tabs
            examsTab = tabs[0] as ExamsTabViewModel;
            compareTab = tabs[1] as CompareExamsTabViewModel;
            templatesTab = tabs[2] as TemplatesTabViewModel;
        }

        [TestMethod]
        public void TestTabTypes()
        {
            Assert.IsInstanceOfType(tabs[0], ExamsTabViewModel);
            Assert.IsInstanceOfType(tabs[1], CompareExamsTabViewModel);
            Assert.IsInstanceOfType(tabs[2], TemplatesTabViewModel);
        }

但是在断言中,类型给出了错误:

'ExamsTabViewModel' is a type, which is not valid in the given context.

即使断言的签名是

void Assert.IsInstanceOfType(object value, Type expectedType)

为什么这不起作用?

尝试将断言更改为 Assert.IsInstanceOfType(tabs[0], typeof(ExamsTabViewModel)),因为您需要提供 Type 的实例,而不是类型名称。

你想要在 实例 Type class 中,而不是类型名称。从后者获得前者的一种简单方法是 typeof:

    [TestMethod]
    public void TestTabTypes()
    {
        Assert.IsInstanceOfType(tabs[0], typeof(ExamsTabViewModel));
        Assert.IsInstanceOfType(tabs[1], typeof(CompareExamsTabViewModel));
        Assert.IsInstanceOfType(tabs[2], typeof(TemplatesTabViewModel));
    }