我有一个笔试题目,需要给下面这样一个类写单元测试
有哪位高手或者前辈能帮忙指点一下么 ?
小弟水平不够,实在是不太会呀
public class CouponManager
{
private readonly ILogger _logger;
private readonly ICouponProvider _couponProvider;
public CouponManager(ILogger logger, ICouponProvider couponProvider)
{
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
_couponProvider = couponProvider ?? throw new ArgumentNullException(nameof(couponProvider));
}
public async Task<bool> CanRedeemCoupon(Guid couponId, Guid userId, IEnumerable<Func<CouponManager, Guid, bool>> evaluators)
{
if (evaluators == null)
throw new ArgumentNullException(nameof(evaluators));
var coupon = await _couponProvider.Retrieve(couponId);
if (coupon = null)
throw new KeyNotFoundException();
if (!evaluators.Any())
return true;
bool result = false;
foreach (var evaluator in evaluators)
result |= evaluator(coupon, userId);
return result;
}
}
非常感谢了:)
Nunit测试i用的,具体参数看你程序少CouponProvider类,看情况修改吧!
本质单元测试就是测试预期情况和实际执行是不是你想要的结果!
[Test()]
public void TestCtor()
{
var ex = Assert.Catch<ArgumentNullException>(() => new CouponManager(null, null));
Assert.AreEqual(ex.ParamName, "logger");
ex = Assert.Catch<ArgumentNullException>(() => new CouponManager(LogManager.GetCurrentClassLogger(), null));
Assert.AreEqual(ex.ParamName, "couponProvider");
}
[Test]
public void TestCanRedeemCoupon()
{
var cm1 = new CouponManager(LogManager.GetCurrentClassLogger(), new CouponProvider());
var ex = Assert.CatchAsync<ArgumentNullException>(() => cm1.CanRedeemCoupon(Guid.NewGuid(), Guid.NewGuid(), null));
Assert.AreEqual(ex.ParamName, "evaluators");
var evaluators = new List<Func<CouponManager, Guid, bool>>();
Assert.Catch<KeyNotFoundException>(() => cm1.CanRedeemCoupon(Guid.Empty, Guid.NewGuid(), evaluators));
var xx = Guid.NewGuid();
Task<bool> r1;
r1 = cm1.CanRedeemCoupon(xx, Guid.NewGuid(), evaluators);
Assert.IsTrue(r1.Result);
evaluators.Add((manager, guid) => true);
r1 = cm1.CanRedeemCoupon(xx, Guid.NewGuid(), evaluators);
Assert.IsTrue(r1.Result);
evaluators.Add((manager, guid) => false);
r1 = cm1.CanRedeemCoupon(xx, Guid.NewGuid(), evaluators);
Assert.IsFalse(r1.Result);
}
你好,我这个主要是在单元测试中,要测试抛出的各种异常
请问怎么处理, 单元测试中如何写测试方法来测试上面的各种异常情况