简体   繁体   English

重载方法的单元测试

[英]Unit Test on overloaded method

I have been battling with writing some unit test for some of our code and I am struggling with this one: 我一直在努力为我们的一些代码编写一些单元测试,我正在努力解决这个问题:

We have a method that we overloaded and it is like this: 我们有一个我们重载的方法,它是这样的:

 Public Client GetClient(int productID)
 {
  //Some sql that evaluate a client

  if(!GetClient(clientRef,ClientTypeRef))
   Return Client.UnknownClient;
    //some other sql and codes
  Return Client.CustomerClient;
  }

The problem is how do I approach this, in my test I tried to add a mock to the GetClient(clientRef,ClientTypeRef) and returning an OK Client (anything other than Client.UnknownClient ) to allow me to continue but I am getting a null reference? 问题是如何处理这个问题,在我的测试中,我试图将模拟添加到GetClient(clientRef,ClientTypeRef)并返回一个OK客户端( Client.UnknownClient以外的任何东西)以允许我继续但是我得到一个null参考? Is it possible to mock and test such methods, and how would I continue with this. 是否有可能模拟和测试这样的方法,我将如何继续这样做。

One of the reasons why unit testing has become so popular was that it was shown to encourage SOLID design principles . 单元测试变得如此受欢迎的原因之一是它被证明可以鼓励SOLID设计原则

Based on the little piece of code you've included, I think your difficulty may come from the fact that your GetClient(int productID) has too many responsibilities so you're struggling to test them separately. 基于你所包含的一小段代码,我认为你的困难可能来自于你的GetClient(int productID)有太多的责任,所以你很难分别测试它们。

The way I understand it, you are: 我理解它的方式,你是:

  • loading a client from the DB (by product Id?) 从DB加载客户端(按产品ID?)
  • checking (with complex logic involving more queries to the db?) what kind of client it is 检查(复杂的逻辑涉及对数据库的更多查询?)它是什么类型的客户端

Rather than mocking GetClient(clientRef,ClientTypeRef) so that you can test every logical path under it, I would encourage you (if possible) to try and refactor your code, so that you separate the loading of the client from the checking of the client's type and possibly also some of the logic you group under //some other sql and codes . 我可以鼓励你(如果可能的话)尝试重构你的代码,而不是GetClient(clientRef,ClientTypeRef)以便你可以测试它下面的每个逻辑路径,这样你就可以将客户端的加载与客户端的检查分开了。键入,也可能还有一些逻辑分组//some other sql and codes

That should make it easier to test every piece separately, but above all would make your code more maintainable. 这应该可以更容易地分别测试每个部分,但最重要的是使您的代码更易于维护。

What mocking frame work are you using? 你使用什么模拟框架工作?

I use moq , to mock this method you would do something like 我使用moq来模拟这种方法你会做类似的事情

 _mockClientRepository.Setup(x => x.GetClient(It.IsAny<int>(),It.IsAny<int>())).Returns(Client.CustomerClient);

Basically this means that any integer passed to the method will always return Client.CustomerClient 基本上这意味着传递给方法的任何整数都将返回Client.CustomerClient

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM