我为我的代码编写了这个简单的测试用例。
module CustomerTests
open Xunit
open FsUnit
open MyProject.Customer
open MyProject.Customer.Domain
module ``When upgrading customer`` =
let customerVIP = {Id = 1; IsVip = true; Credit = 0.0M}
let customerSTD = {Id = 2; IsVip = false; Credit = 100.0M}
[<Fact>]
let ``should give VIP customer more credit`` () =
let expected = {customerVIP with Credit = customerVIP.Credit + 100.0M }
let actual = upgradeCustomer customerVIP
actual |> should equal expected非常令人惊讶的是,这段代码出错了。
[xUnit.net 00:00:00.64] CustomerTests+When upgrading customer.should give VIP cstomer more credit [FAIL]
Failed CustomerTests+When upgrading customer.should give VIP cstomer more credit [3 ms]
Error Message:
System.NullReferenceException : Object reference not set to an instance of an object.
Stack Trace:
at CustomerTests.When upgrading customer.should give VIP cstomer more credit() in /Users/user/code/fsharp/CustomerProject/CustomerTests.fs:line 12但是第12行只是一个正在创建的记录,因此该行不可能抛出对象引用,而不是设置为对象实例。这完全让我费解。
在dotnet fsi repl中,我可以执行我的所有方法,并且在我的函数中没有对象引用问题,这是从这里的测试中调用的。
发布于 2022-10-28 02:23:04
正如this SO answer解释的那样,XUnit以跳过这些值初始化的方式加载测试。一个简单的解决方法是使用一个类而不是一个模块:
type ``When upgrading customer``() =
let customerVIP = {Id = 1; isVip = true; Credit = 0.0M}
let customerSTD = {Id = 2; isVip = false; Credit = 100.0M}
[<Fact>]
let ``should give VIP cstomer more credit`` () =
let expected = {customerVIP with Credit = customerVIP.Credit + 100.0M }
let actual = upgradeCustomer customerVIP
actual |> should equal expected这样,这些值的初始化就会按应有的方式进行。
https://stackoverflow.com/questions/74229814
复制相似问题