【问题标题】:Error CS0119; class is a type, which is not valid in the given context错误 CS0119; class 是一种类型,在给定的上下文中无效
【发布时间】:2021-09-02 05:57:11
【问题描述】:

熟悉 C# 后,我在进行断言的行上进行单元测试时遇到以下错误 Assert.IsInstanceTypeOf

Error CS0119 'Product' is a type, which is not valid in the given context

创建类型的事情已经完成。是什么导致了这个错误?

UnitTest1.cs

using Microsoft.VisualStudio.TestTools.UnitTesting;
using ProductNamespace;

namespace TestProject2
{
    [TestClass]
    public class TestProduct
    {
        [TestMethod]
        public void TestNewProduct()
        {
            Product mock_product = new Product(4.95);
            Assert.IsInstanceOfType(mock_product, Product);
        }
    }
}

Product.cs

namespace ProductNamespace
{
    public class Product
    {
        private double price;

        public Product(double price)
        {
            this.price = price;
        }
    }
}

【问题讨论】:

  • “创建类型的事情已经执行”是什么意思?
  • 我从头开始创建了一个单元测试项目。设置单元测试后,Visual Studio 会提示生成新类型。我只是在传达我已经做到了。
  • 好的 - 听起来您认为这与错误有关。

标签: c# unit-testing mstest


【解决方案1】:

您似乎正在尝试使用IsInstanceOfType(object, Type) 方法。为此,您需要提供一个Type 参数,但目前您只是直接指定了类名。这不是一个有效的 C# 表达式 - 您需要使用 typeof operator 从类名中获取 Type

Assert.IsInstanceOfType(mock_product, typeof(Product));

请注意,这确实不是一个有用的测试 - 您没有测试任何有关代码的内容,您实际上是在询问 .NET 是否正常运行。如果代码到达该行(即,如果构造函数没有抛出异常),那么它绑定可以通过 - 因为new Xyz 的结果始终是Xyz。 (COM 接口有一些边缘情况,但这里不相关。)

【讨论】:

    【解决方案2】:
    Assert.IsInstanceOfType(mock_product, typeof(Product));
    

    请尝试以上方法。根据official documentation,第二个参数应该是Type

    【讨论】:

    • 当我开始写答案时,第一个答案并不存在。我是在提交答案后才意识到这一点的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-07
    • 2020-04-16
    • 2020-07-10
    • 2018-08-09
    • 2016-03-30
    • 2021-01-19
    • 1970-01-01
    相关资源
    最近更新 更多