Open htzhang2 opened 3 years ago
I have the same request. We're using xUnit and Moq and have the same issue.
The constructor generates the mock dependencies like this:
_systemService = new Mock<ISystemService>().Object;
instead of
_systemService = new Mock<ISystemService>();
As a result, when we go to fill in one of the Method stub functions, we can't use the mocks effectively because we can't set them up for the specific tests.
Seems like a better approach would be to define the mocks as actual mocks like:
private Mock<ISystemService> _systemService;
and then in the test you would have the ability to Setup the mock and then use it as _systemService.Object
Sorry I didn't see this until now. It makes sense - I just don't particularly use Moq, so hadn't twigged. I will see what I can do to fix it when I have some time. I don't work for sentryone any more, though, so I'll have to fix it on a fork 👍
Thanks for the response @mattwhitfield. I actually did find a workaround that works really well for xUnit using Moq. You can use the Mock.Get
function to get the mock version of your object.
Here's a pseudocode example in case someone else runs into this. If you have the dependency defined like this from the test generator:
_dependencyService = new Mock<ISomeService>().Object;
and then you want to set up a mock version of a function on that, you can do the following:
Mock.Get(_dependencyService).Setup(s => s.SomeFunction()).Returns(someValue);
Thanks for the feedback. I still think your idea of generating it correct in the first place is the way to go 👍
@mrsuau627 I'm going to have to re-release this project, as I don't have access to update the original marketplace image, but just wanted to let you know that this is fixed in https://github.com/mattwhitfield/unittestgenerator - and I'm hoping to get the release out in the next couple of weeks.
Fixed in https://marketplace.visualstudio.com/items?itemName=MattWhitfield.Unitverse - please open a new issue on https://github.com/mattwhitfield/unittestgenerator/issues if there is still a problem 👍
Currently, class dependency is generated as interface variable.
I'd like an option to generate dependency as mocked interface. Reason is I want to setup and verify mocked method later
Sample source code: public class Parent { private IChild child; public Parent(IChild child) { this.child = child; } public void DoSomething() { this.child.DoSomething(); } }
Expected unit test:
public class ParentTests { private Parent _testClass; private Mock\<IChild> _childMock;
[TestInitialize] public void SetUp() { _childMock = new Mock\<IChild>(); _testClass = new Parent(_child.object); } ... }
Actual Unit test generated:
public class ParentTests { private Parent _testClass; private IChild _child;
[TestInitialize] public void SetUp() { _child = new Mock().Object;
_testClass = new Parent(_child);
}
...
}